javascript - 无法在新打开的窗口 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) 它什么也不显示并且脚本停在那里。
解决方案
由于(XSS [Cross Site Scripting])错误,您的代码将无法工作。Firefox 阻止您更改不同域的内容。
由于您正在打开一个新窗口,因此您现在拥有的域名 (about:blank) 与您开始使用的域名不同。
有几种方法可以解决这个问题,很快就会想到使用window.create
API并使用查询参数将数据传递到新窗口:
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
将消息传递回后台脚本,然后再传递到新窗口。
或者您可能会在页面本身中注入一个弹出窗口并执行类似的操作。
推荐阅读
- typescript - 打字稿字符串拆分删除引号
- android-source - 如何制作指定JDK版本的AOSP模块?
- javascript - ReactJS 和 Redux - TypeError:state.reduxCart 不可迭代
- java - Young GC发生时,ext root扫描需要很长时间。可能的原因是什么?
- javascript - 你好,我的目标是,当我点击“创建复选框”按钮时,它会自动创建一个带有 ID 的复选框,而不使用输入类型文本
- jquery - 使用动画的 jQuery 滚动到 div 在 safari 中无法正常工作
- android - 如何通过特定端口路由我的 android 应用程序的互联网数据?
- android - 类在firebase消息颤动上找不到异常
- azure - Azure 设置递归 ACL 导致 403 - 虽然更新没问题
- python - 显示来自 tensorflow 数据集类的图像