在window.open()生成的窗口中执行JavaScript

Execute JavaScript in window.open() generated window

本文关键字:窗口 执行 JavaScript window open      更新时间:2023-09-26

我的问题似乎如下:

我有这个代码:

function openNew(theImage){
    var theHTML = "<!doctype html><html><head><script src='../js/windowScript.js'></script><title>EditWindow</title></head><body><div id='canvasContainer'></div><img id='removeable' src='"+theImage+"'><button id='cropMe'>Crop it!</button></body></html>";
    var editWindow = window.open("","","width=1000 height=800 titlebar=0");

    editWindow.document.write(theHTML);
}

它打开了一个包含"theHTML"-字符串内容的新窗口。正如您所看到的,它还将脚本"windowScript.js"添加到新窗口中。

windowScript.js:

window.onload = function(){
    document.getElementById("cropMe").addEventListener("click",removeImg);
    alert("it began");
}
function removeImg(){
    var imgTAG = document.getElementById("removeable");
    var imgURL = imgTAG.getAttribute("src");
    if(imgTAG.parentNode)
        imgTAG.parentNode.removeChild;
}

但是这个脚本永远不会被执行。如果我通过chrome的检查器检查脚本,它会告诉我它在那里,甚至会检测其中是否有错误,但无论如何都不会执行。

有没有一种变通方法可以让脚本在新窗口中运行,而无需通过editWindow.document.write();注入?

提前感谢您的支持!

再次更新并实际测试了代码。

windowScript.js

function removeImg(myWindow){
    var imgTAG = myWindow.document.getElementById("removeable");
    var imgURL = imgTAG.getAttribute("src");
    if(imgTAG.parentNode) {
        imgTAG.parentNode.removeChild(imgTAG);
        console.log(imgURL);
    }
    else {
        console.log("fail");
    }
}
function openNew(theImage){
    var theHTML = "<!doctype html><html>" +
                  "<head><title>EditWindow</title></head><body>" +
                  "<div id='canvasContainer'></div><img id='removeable' src='"+theImage+"'>" +
                  "<button id='cropMe'>Crop it!</button></body></html>";
    var editWindow = window.open("","","width=1000 height=800 titlebar=0");
    editWindow.document.write(theHTML);
    editWindow.document.getElementById("cropMe").addEventListener("click",function(){ removeImg(editWindow); });
}

windowtest.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>WindowTest</title>
    <script src="windowScript.js"></script>
</head>
<body>
<a href="javascript:openNew('Capture.PNG')">open window</a>
</body>
</html>

您需要调用editWindow.docent.close();