7

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?

Leslie Wu
  • 760
  • 3
  • 13
  • 29
  • possible duplicate of [Building a Chrome Extension - Inject code in a page using a Content script](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) – Xan Dec 12 '14 at 10:52
  • Or even better with regards to your questions in comments: [Executing code at page-level from Background.js and returning the value](http://stackoverflow.com/questions/26140443/executing-code-at-page-level-from-background-js-and-returning-the-value/26141393) – Xan Dec 12 '14 at 10:53

1 Answers1

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);
KAdot
  • 1,997
  • 13
  • 21