admin管理员组

文章数量:1356265

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?

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?

Share Improve this question edited Mar 20, 2013 at 8:23 Leslie Wu asked Mar 20, 2013 at 7:40 Leslie WuLeslie Wu 7703 gold badges14 silver badges29 bronze badges 2
  • possible duplicate of Building a Chrome Extension - Inject code in a page using a Content script – Xan Commented Dec 12, 2014 at 10:52
  • Or even better with regards to your questions in ments: Executing code at page-level from Background.js and returning the value – Xan Commented Dec 12, 2014 at 10:53
Add a ment  | 

1 Answer 1

Reset to default 7

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);

本文标签: javascriptExecute web page js from chrome extension content scriptStack Overflow