Luckey Luckey - 2 months ago 10
Javascript Question

Execute JavaScript in window.open() generated window

My problems seem to be the following:

I have this code:

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


which opens a new window with the "theHTML"-Strings content.
And as you can see, it also adds the script "windowScript.js" to the new 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;

}


but this script is never executed.
If I check the script via the inspector of chrome, it tells me it's there and it even detects if there are errors in it, but it does not get executed whatsoever.

Is there a workaround to get the script running in the new window, without injecting it via
editWindow.document.write();

?

Thank you in advance for your support!

Answer

UPDATED again and actually tested the code.

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>
Comments