Running JavaScript in New Window.Open

Running Javascript in new window.open

Scripts added with .innerHTML aren't executed. You need to create a script node and append it to the window's DOM.

$("#button").click(newWindow);
function newWindow(id) { var html = $(id).html(); var win = window.open(''); win.document.head.innerHTML = '<title>Hi</title></head>'; win.document.body.innerHTML = '<body>' + html + '</body>'; var script = document.createElement('script'); script.src = 'js/myScript.js'; win.document.head.appendChild(script);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button id="button">Click me</button>

How can I run a script in another (newly-opened) tab?

Instead of embedding script element in the document, do this.

  • wrap the code that you want to run in another tab, into a function.
  • bind that wrapped function to the new tab's window
  • Call that function

Here's the code that I ran in my console and it worked for me i.e another tab was opened and alert was displayed.

function openAndPush(url, id) {
var win = window.open('https://www.google.com');
win.test = function () {
win.alert("Starting magic...");

}
win.test();
setTimeout(function () {
win.document.body.appendChild(element);
console.log('New script appended!')
}, 10000);
}

Execute JavaScript in window.open() generated window

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>

How to call a function of another window in javascript?

var a = window.open("mypage.html", "_blank");
a.focus();

a.addEventListener('load', function(){
a.myfunction("hi");
}, true);


Related Topics



Leave a reply



Submit