Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute web page js from chrome extension content script

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?

like image 619
Leslie Wu Avatar asked Mar 20 '13 07:03

Leslie Wu


People also ask

Can I use Axios in Chrome extension?

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.

What is content JS in Chrome extension?

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.

What is Chrome scripting executeScript?

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.


1 Answers

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);
like image 51
KAdot Avatar answered Oct 02 '22 16:10

KAdot