Chrome 扩展中的 JavaScript 注入
我是“chrome 扩展开发”的新手,我想制作一个扩展。
当用户单击弹出页面上的按钮时,该扩展必须在网页中注入代码。我看到了关于此的不同主题,但似乎不可能注入与网页现有代码“交互”的代码。例如:当用户打开网页时会创建一个名为 test 的变量,我想获取该变量并在我的代码中使用它(例如:alert(test);)。我尝试了多种方法来实现这一目标,但它不起作用。我该怎么做?我尝试过:
chrome.tabs.executeScript(null,{code:"alert('test')"});
console.log("alert('test');");
这有效,但仅适用于弹出页面,因此变量“test”不存在。
I'm new with 'chrome extension development', and I wanted to make a extension.
That extension has to inject code in a web page when the user clicks a button on the popup-page. I saw different subjects about that, but it doesn't seem to be possible to inject code that 'interacts' with the existing code of the web page. For example: a variable called test is made when the user opens a web page, I want to get that variable and use it in my code (for example: alert(test);). I tried several ways to achieve this, but it won't work. How can I do this? I tried:
chrome.tabs.executeScript(null,{code:"alert('test')"});
console.log("alert('test');");
This worked, but only for the popup page and so the variable 'test' didn't exist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
谢谢,它现在可以工作了,这是我的代码:
Popup:
contentScript:
Thanks, it's working now, here is my code:
Popup:
contentScript:
你的看法非常正确。 Chrome 扩展程序代码无法直接与现有页面的代码交互 - 它们运行在不同的、隔离的环境中。
不过,它们共享的是 DOM 结构和 (HTML5) localStorage,因此您可以使用其中之一来相互传递消息,例如通过定义 DOM 更改的侦听器。
Your perception is very true. Chrome extension code cannot interact directly with the existing page's code - they run in different, secluded environments.
What they do share, though, is the DOM structure and (HTML5) localStorage, so you can use one of those to pass messages to each other, e.g. by defining listeners for DOM changes.