问题
I'm having trouble creating a new window and adding content from my extension. Since I can't call window.open from my script without losing a reference to my new window, I'm forced to use chrome.windows.create.
Essentially what I want is this:
var newWindow = window.open();
newWindow.document.writeln( 'hello world' );
To create the equivalent in my chrome extension, i'm trying this:
chrome.windows.create({ type: 'popup' } , function(newWindow) {
newWindow.tabs[0].executeScript(null, { code: 'document.write("hello world");' })
});
The new window is created, however I can't seem to access the document object of the newly created window.
回答1:
Problems in your code
- If you create a new window without any
URL
, it will create two windows withchrome://newtab
and ablank popup window
. - You have to use chrome.tabs.executeScript with correct parameters not
newWindow.tabs[0].executeScript
Working Version
chrome.windows.create({
type: 'popup',
url: "https://www.google.co.in/"
}, function (newWindow) {
console.log(newWindow);
chrome.tabs.executeScript(newWindow.tabs[0].id, {
code: 'document.write("hello world");'
});
});
来源:https://stackoverflow.com/questions/14373478/create-new-window-and-insert-dynamic-content-in-chrome-extension