可以从 Chrome 扩展程序修改窗口对象吗? [英] Can the window object be modified from a Chrome extension?
问题描述
我想制作一个 Chrome 扩展程序,在 window
内提供一个新对象.当在加载了扩展程序的浏览器中查看网页时,我希望 window.mything
可以通过 Javascript 访问.window.mything
对象将有一些我将在扩展中定义的函数,这些函数应该可以在查看页面时从 console.log
或任何 Javascript 文件中调用在启用了扩展的浏览器中.
I would like to make a Chrome extension that provides a new object inside window
. When a web page is viewed in a browser with the extension loaded, I would like window.mything
to be available via Javascript. The window.mything
object will have some functions that I will define in the extension, and these functions should be callable from console.log
or any Javascript file when the page is viewed in a browser with the extension enabled.
通过使用内容脚本:
var s = document.createElement("script");
s.src = chrome.extension.getURL("mything.js");
document.getElementsByTagName("head")[0].appendChild(s);
mything.js 看起来像这样:
mything.js looks like this:
window.mything = {thing: true};
console.log(window);
每当页面加载时,我都会看到整个 window
对象,正如我期望它在控制台中一样.但是,我无法从控制台与 window.mything
对象交互.似乎注入的脚本并没有真正修改全局 window
对象.
Whenever a page loads, I see the entire window
object as I expect it to be in the console. However, I can't interact with the window.mything
object from the console. It seems at if the injected script hasn't really modified the global window
object.
如何从 Chrome 扩展程序修改全局 window
对象?
How can I modify the global window
object from a Chrome extension?
推荐答案
你不能,不能直接.来自内容脚本文档:
You can't, not directly. From the content scripts documentation:
但是,内容脚本有一些限制.他们不能:
However, content scripts have some limitations. They cannot:
- 使用 chrome.* API(chrome.extension 的部分除外)
- 使用由其扩展页面定义的变量或函数
- 使用由网页或其他内容脚本定义的变量或函数
(强调)
内容脚本看到的 window
对象与页面看到的 window
对象不同.
The window
object the content script sees is not the same window
object that the page sees.
您可以通过 DOM 传递消息,但是,使用 window.postMessage
方法.您的页面和内容脚本都会监听 message 事件,每当您从其中一个地方调用 window.postMessage
时,另一个地方都会收到它.内容脚本"文档页面上有一个此示例.
You can pass messages via the DOM, however, by using the window.postMessage
method. Both your page and content script listen to the message event, and whenever you call window.postMessage
from one of those places, the other will receive it. There's an example of this on the "Content Scripts" documentation page.
您可以通过从内容脚本中注入脚本来向页面添加一些方法.尽管如此,它仍然无法与扩展的其余部分进行通信,而不使用诸如 postMessage
之类的东西,但您至少可以向页面的 window
添加一些内容
edit:
You could potentially add some methods to the page by injecting a script from the content script. It still wouldn't be able to communicate back with the rest of the extension though, without using something like postMessage
, but you could at least add some things to the page's window
var elt = document.createElement("script");
elt.innerHTML = "window.foo = {bar:function(){/*whatever*/}};"
document.head.appendChild(elt);
这篇关于可以从 Chrome 扩展程序修改窗口对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!