将代码直接放在弹出窗口功能中

时间:2018-11-08 15:41:19

标签: javascript html

例如,我有这个脚本

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
var myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>

代替

 myWindow.document.write("<p>This is 'myWindow'</p>");

我想放类似的东西

 myWindow.document.write("<script> alert("h");</script>");

由于某些情况,我无法链接到其中包含代码的另一页。放置脚本会使窗口甚至无法打开。谢谢

2 个答案:

答案 0 :(得分:1)

  1. 报价
  2. 关闭文档(myWindow.document.close()
  3. 转义</script>脚本标记中不能包含</script>
  4. 从不document.write到已渲染的页面中

类似这样的东西

function myFunction() {
  var myWindow = window.open("", "myWindow", "width=200,height=100");
  myWindow.document.write("<p>This is 'myWindow'</p>");
  myWindow.document.close();
  var p = document.createElement("p")
  p.innerHTML = "This is the source window!";
  myWindow.opener.document.querySelector("body").appendChild(p); // same as document.querySelector("body") 
}

如果要使用脚本,则需要

var myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<script>alert('h')<\/script>"); // MANDATORY ESCAPE \/SCRIPT
myWindow.document.close();

答案 1 :(得分:0)

用双引号代替您的内容,用单引号包裹

test
相关问题