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

Execute JavaScript in window.open() generated window

我的问题似乎是:

我有这个代码:

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

这会打开一个新的 window,其中包含 "theHTML"-Strings 内容。 如您所见,它还将脚本 "windowScript.js" 添加到新的 window.

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 的检查器检查脚本,它会告诉我它在那里,甚至会检测其中是否有错误,但无论如何都不会执行。

是否有解决方法可以在新 window 中获取脚本 运行,而不通过 editWindow.document.write(); 注入它 ?

在此先感谢您的支持!

UPDATED 并实际测试了代码。

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.document.close();