Create new window and insert dynamic content in Chrome Extension

偶尔善良 提交于 2021-02-05 08:26:47

问题


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 with chrome://newtab and a blank 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!