[英]Execute web page js from chrome extension content script
I have this js function in my web page html code. 我在我的网页html代码中有这个js函数。
function update() {
document.getElementById( "textbox ").value = updatetext;
}
When I execute "update()" from chrome console, it works. 当我从chrome控制台执行“update()”时,它可以工作。
But if I execute from chrome extension, 但是如果我从chrome扩展程序执行,
chrome.tabs.executeScript(tab.id, {code: "update();"}, function(result){});
It says update is not defined. 它说没有定义更新。 But if I replace with "alert('ok')", It works. 但如果我用“alert('ok')替换”,它就有效。
Then I execute 然后我执行
eval("update()")
in Chrome extension content script. 在Chrome扩展程序内容脚本中。 It also says "update is not defined." 它还说“未定义更新”。
So what can i do to call js function on web page? 那么我该怎么做才能在网页上调用js函数呢?
Chrome executes content scripts in a sandbox, so you need to inject an inline script to interact with the webpage: Chrome在沙箱中执行内容脚本,因此您需要注入内联脚本以与网页进行交互:
var injectedCode = 'update()';
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ injectedCode +')();'));
(document.body || document.head || document.documentElement).appendChild(script);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.