在新窗口中运行 Javascript.open

IT技术 javascript jquery html
2021-03-05 13:28:07

我正在运行此功能以打开一个新窗口。

function htmlNewWindow(id) {
    var html = $(id).html();
    var newWindow = window.open('');
    newWindow.document.body.innerHTML =  '<html><head><title>Hi</title>  <script src="js/myScript.js"></script> </head>' + html;    
}

这成功地创建了一个包含 HTML 的新窗口。我有一堆 HTML 标签,单击它们时会运行一个名为 Foo1 的函数。我尝试将 Foo1 的整个函数打印到新的 HTML 文档中,并尝试将 Foo1 放入 myScript.js。我在新窗口的脚本标签中看到了 Foo1,但都没有加载,因为它们只是作为 HTML 写入新页面。

4个回答

.innerHTML不执行添加的脚本您需要创建一个script节点并将其附加到窗口的 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>

这不在 Stack Snippet 的沙箱中运行,这是一个有效的jsfiddle

谢谢这有效,我正在寻找解决方案的错误位置。我不知道我可以以这种方式将新节点类型附加到新窗口。再次感谢!
2021-04-28 13:28:07
我想知道纯 JS 替代品。
2021-05-13 13:28:07
@Y.Yoshii$(id).html()改为document.getElementById(id).innerHTML
2021-05-18 13:28:07

试试这个:

var newWindow = window.open('');
newWindow.document.createElement('script');
script.src = 'js/myScript.js';
newWindow.document.head.appendChild(script);

以防万一有人要在链接中完成此操作。请执行下列操作:

<a href="javascript: var n= window.open('/url/to/page/in/SAMEDOMAIN'); n.focus(); n.addEventListener('load', n.alert('replace this with a good thing'), true);">Link</a>

这将打开一个带有该 URL 的新窗口,它将焦点设置到该窗口,并且一旦触发 'load' 事件,它就会执行函数中的代码。它仅适用于同一域中的页面。

希望这有助于⬆✌。

干杯👍

以下是您创建并在新窗口中附加脚本文件的方法:

var fileref = document.createElement('script');
//creates script in current document
fileref.setAttribute("type", "text/javascript")
//set it to JS by "type"
fileref.setAttribute("src", filename)
//set your "src=yourFile_href_Here.js" 


//Then create your newWindow as you did above, but slightly updated
//Create your function which will consume the "fileref" argument
function htmlNewWindow(fileref) {
    var newWindow = window.open('');
    newWindow.document.getElementsByTagName("head")[0].appendChild(fileref);
}; //right now the function is made but you still have to execute it

//Execute your function, and pass it the variable "fileref" that you set above.    

htmlNewWindow(fileref);
//Within this edit you will append the head element
//with your newly created script(or any other parameterized argument)

/* Replace your filename to pass any other script */

注意 - 打开位于不同域中的页面,如果没有特别允许,将因 CORS(https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS而拒绝这种情况

如果您的域没有发送脚本,那么将脚本发送到其他人的页面或允许它们进入您自己的页面并不是一种安全的做法。此外,根据您的服务器/技术堆栈,您可能需要在后端堆栈中配置 *-origin 设置。请参阅此处:(https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy