Omar Stewey
Omar Stewey

Reputation: 224

Create new window and insert dynamic content in Chrome Extension

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.

Upvotes: 3

Views: 5492

Answers (1)

Sudarshan
Sudarshan

Reputation: 18544

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");'
    });
});

Upvotes: 4

Related Questions