Veselin
Veselin

Reputation: 67

Can't access document on new open window JS

I am trying to get some data from a webpage and pass it to new window and print it from there. Here is my code:

var print_btn;
let win;

document.getElementsByTagName('html')[0].innerHTML = document.getElementsByTagName('html')[0].innerHTML +"<button class=\"printbuton\">Print Button</button>";

print_btn = document.getElementsByClassName('printbuton')[0];

print_btn.onclick = function() {
    
    console.log("check 1");
    
    var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
    console.log("check 2");
    WinPrint.document.write('Print this');
    console.log("check 3");
    WinPrint.document.write('Print that');
    WinPrint.document.write('and this');
    
    console.log("button pushed");
}

When I try this it opens the new window, but it stays empty and in console it logs only "check 1" and "check 2". I tested that if i console.log(WinPrint) it shows in console, but if I do console.log(WinPrint.document) it doesn't show anything and the script stops there.

Upvotes: 0

Views: 559

Answers (1)

cameck
cameck

Reputation: 2098

Your code will not work due to a (XSS [Cross Site Scripting]) Error. Firefox is preventing you from altering the content of a different domain.

Since you're opening a new window, you now have a different domain name (about:blank) than the one you started on.

There's a few ways to go about this, what comes quickly to mind would be to use the window.create API and use query params to pass the data to the new window:

function onCreated(windowInfo) {
  console.log('SUCCESS');
}

function onError(error) {
  console.log(`Error: ${error}`);
}

print_btn.addEventListener('click', event => {

  var popupURL = browser.extension.getURL("popup/popup.html?line=blahblah&line2=loremipsum");

  var creating = browser.windows.create({
    url: popupURL,
    type: "popup",
    height: 200,
    width: 200
  });
  creating.then(onCreated, onError);

});

Or you could do something more elaborate by opening using windows.create, then using runtime.sendmessage to pass messages back to the background script and then to the new window.

OR you could probably inject a popup into the page itself and do something similiar.

Upvotes: 1

Related Questions