可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
I was able to successfully inject a Javascript file into the page by using a Content Script:
var s = document.createElement("script");
s.src = chrome.extension.getURL("mything.js");
document.getElementsByTagName("head")[0].appendChild(s);
mything.js looks like this:
window.mything = {thing: true};
console.log(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.
How can I modify the global window
object from a Chrome extension?
回答1:
You can't, not directly. From the content scripts documentation:
However, content scripts have some limitations. They cannot:
- Use chrome.* APIs (except for parts of chrome.extension)
- Use variables or functions defined by their extension's pages
- Use variables or functions defined by web pages or by other content scripts
(emphasis added)
The window
object the content script sees is not the same window
object that the page sees.
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.
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);
回答2:
I've been playing around with this. I found that I can interact with the window object of the browser by wrapping my javascript into a window.location= call.
var myInjectedJs = "window.foo='This exists in the \'real\' window object';"
window.location = "javascript:" + myInjectedJs;
var myInjectedJs2 = "window.bar='So does this.';"
window.location = "javascript:" + myInjectedJs2;
It works, but only for the last instance of window.location being set. If you access the document's window object, it will have a variable "bar" but not "foo"
回答3:
Content Scripts can call window
methods which can then be used to mutate the window
object. This is easier than <script>
tag injection and works even when the <head>
and <body>
haven't yet been parsed (e.g. when using run_at: document_start
).
// In Content Script
window.addEventListener('load', loadEvent => {
let window = loadEvent.currentTarget;
window.document.title='You changed me!';
});
回答4:
A chrome extension's content_script
runs within its own context which is separate from the window. You can inject a script into the page though so it runs in the same context as the page's window, like this: Chrome extension - retrieving global variable from webpage
I was able to call methods on the window object and modify window properties by essentially adding a script.js
to the page's DOM:
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.remove();
};
and creating custom event listeners in that injected script file:
document.addEventListener('_my_custom_event', function(e) {
// do whatever you'd like! Like access the window obj
window.myData = e.detail.my_event_data;
})
and dispatching that event in the content_script:
var foo = 'bar'
document.dispatchEvent(new CustomEvent('_save_OG_Editor', {
'detail': {
'my_event_data': foo
}
}))
or vice versa; dispatch events in script.js
and listen for them in your extension's content_script (like the above link illustrates well).
Just be sure to add your injected script within your extension's files, and add the script file's path to your manifest within "web_accessible_resources"
or you'll get an error.
Hope that helps someone \ (•◡•) /
回答5:
As others pointed out, context scripts do not run in the same context as the page's, so, to access the correct window
, you need to inject code into the page.
Here's my take at it:
function runEmbedded() {
// Put here whatever your script needs to do. For example:
window.foo = "bar";
}
function embed(fn) {
const script = document.createElement("script");
script.text = `(${fn.toString()})();`;
document.documentElement.appendChild(script);
}
embed(runEmbedded);
Clean and easy to use. Whatever you need to run in the page's context, put it in runEmbedded()
(you may call it whatever you prefer). The embed()
function takes care of packaging your function and sending it to run in the page.