首页 > 解决方案 > 无法在新打开的窗口 JS 上访问文档

问题描述

我正在尝试从网页获取一些数据并将其传递到新窗口并从那里打印。这是我的代码:

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

当我尝试这个时,它会打开新窗口,但它保持为空,并且在控制台中它只记录“检查 1”和“检查 2”。我测试了如果我 console.log(WinPrint) 它显示在控制台中,但是如果我执行 console.log(WinPrint.document) 它什么也不显示并且脚本停在那里。

标签: javascriptfirefox-addon

解决方案


由于(XSS [Cross Site Scripting])错误,您的代码将无法工作。Firefox 阻止您更改不同域的内容。

由于您正在打开一个新窗口,因此您现在拥有的域名 (about:blank) 与您开始使用的域名不同。

有几种方法可以解决这个问题,很快就会想到使用window.createAPI并使用查询参数将数据传递到新窗口:

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);

});

或者您可以通过打开 using 来做一些更精细的事情windows.create,然后使用runtime.sendmessage将消息传递回后台脚本,然后再传递到新窗口。

或者您可能会在页面本身中注入一个弹出窗口并执行类似的操作。


推荐阅读