[英]Adding and running external javascript file in new window.open()
我想在new window.open()中添加并运行外部javascript文件,因此我在“在new window.open中运行Javascript”中测试了该解决方案,但是该解决方案不起作用。
我的代码在这里:
<input type="button" value="Open a window" onclick="openWindow();">
<script type="text/javascript">
function openWindow()
{
//Open a new window :
var win = window.open("");
//Create script tag :
var script = document.createElement('script');
//Add external javascript file in src attribut of script tag :
script.src = "script.js";
//Append script tag to the new window :
win.document.head.appendChild(script);
}
</script>
名为script.js的外部javascript文件的内容为:
alert("It works !");
当您单击按钮时,会打开一个新窗口,但是不会执行添加的外部javascript文件。
那么如何运行在新打开的窗口中添加的外部javascript文件呢?
使用document.write
const win = window.open('')
win.document.open()
const html = `
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"><\/script>
</head>
<body>
<h1>Test</h1>
<script>alert($('h1').text())<\/script>
</body>
</html>
`
win.document.write(html)
win.document.close()
尝试这个
<script type="text/javascript">
function openWindow()
{
//Open a new window :
var win = window.open("");
//Create script tag :
var script = document.createElement('script'),
div = document.createElement('div');
//Add external javascript file in src attribut of script tag :
script.src = "https://cdnjs.cloudflare.com/ajax/libs/preact/8.3.1/preact.min.js";
script.type = "application/javascript";
script.defer = true;
div.appendChild(script);
win.document.body.appendChild(div);
}
</script>
在新窗口中,打开开发人员控制台并键入preact
您将看到类似{h: ƒ, createElement: ƒ, cloneElement: ƒ, Component: ƒ, render: ƒ, …}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.