I have this js function in my web page html code.
function update() {
document.getElementById( "textbox ").value = updatetext;
}
When I execute "update()" from chrome console, it works.
But if I execute from chrome extension,
chrome.tabs.executeScript(tab.id, {code: "update();"}, function(result){});
It says update is not defined. But if I replace with "alert('ok')", It works.
Then I execute
eval("update()")
in Chrome extension content script. It also says "update is not defined."
So what can i do to call js function on web page?
External modules like axios would need to be bundled into your chrome extension in order for it to work as you intend. You can use a bundler like webpack in order to do this, but there is a decent amount of configuration needed to get up and running. I would recommend using the fetch API as an alternative.
Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.
executeScript() Injects a script into a target context. The script is run at document_idle by default. Note: This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Safari and Firefox 102+, this method is also available in Manifest V2.
Chrome executes content scripts in a sandbox, so you need to inject an inline script to interact with the webpage:
var injectedCode = 'update()';
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ injectedCode +')();'));
(document.body || document.head || document.documentElement).appendChild(script);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With