在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);
}
它打开了一个包含"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();
相关文章:
- 如何准确执行加载脚本&退出弹出窗口
- 如何打开一个新窗口或选项卡,并将其提供给javascript执行
- 在window.open()生成的窗口中执行JavaScript
- Chrome扩展:加载窗口后执行脚本
- 引导:响应式设计-当窗口大小从980px调整到979px时执行JS
- 在显示引导弹出窗口之前执行函数
- 执行angularJS窗口警报不起作用
- JS:执行'失败;getComputedStyle'在'窗口':参数的类型不是'
- 基于浏览器窗口大小的条件 JavaScript 执行
- AngularJS Promise&atop Filter.无法在“窗口”上执行“atob”
- 打印窗口关闭后执行命令
- 执行打开新窗口并执行Javascript
- JavaScript没有在使用ModalPopup(Jquery)的弹出窗口中执行
- 如何仅相对于该框架而不是整个窗口执行javascript
- 从jquery移动对话框窗口执行父函数
- 通过window.open()对另一个窗口执行代码
- 如何从窗口执行函数.没有暴露在窗户上的开瓶器
- 打开window self并为新窗口执行javascript
- Chrome扩展-从弹出窗口执行简单的JavaScript
- 弹出窗口 - 执行操作并关闭