首页 > 解决方案 > 在 window.document.write() 中编写自定义函数

问题描述

目标是在 window.document.write() 中编写一个自定义函数,我想知道这是否可能,我尝试了多种方法在弹出窗口中调用 loadCustomJS() 但我无法做到。

使用外部脚本并在 document.write 中加载将起作用,但是由于 Failed to load resource 上的一些服务器问题:服务器响应状态为 404 (Not Found) ,我正在尝试使用不同的方法在我的 .html 中写入文件本身

在下面的示例代码中,当我尝试使用普通警报时,它可以工作,

downloadWin.document.write('\x3Cscript type="text/javascript"> alert("test") \x3C/script>');

但是,我要触发的目标脚本:downloadWin.document.write('\x3Cscript type="text/javascript"> loadCustomJS() \x3C/script>');

这可能吗 ?

例如代码

<html> ..
<script>

    function loadCustomJS(){
        console.log("TRIGGERING THIS")
        alert("Triggered Function ");
        document.write("<label id='downloadStatus'>Status : Initialising download </label>");
        console.log("Success")
    }

    function _excelExport(){
        var downloadWin = window.open("", "DownloadDialog", "width=430,height=300");
        downloadWin.document.write('<title> Download Window </title>')
        downloadWin.document.write('\x3Cscript type="text/javascript">  loadCustomJS() \x3C/script>');
    }



</script>
..
..
</html>

usingdownloadWin.opener.loadCustomJS()将调用父窗口。但是,我想 document.write("<label id='downloadStatus'>Status : Initialising download </label>");通过调用 loadCustomJS() 函数在子窗口中显示

根据我目前的方法,我能够通过将我的脚本作为文本调用并将其作为脚本附加来做到这一点,如下所示

let sampleRR = loadCustomJS.toString();
var script = document.createElement("script");
script.innerHTML += sampleRR;
script.innerHTML += "runProgram()"
console.log(script)
downloadWin.document.head.append(script)

我想知道是否有更好的方法?

标签: javascripthtml

解决方案


推荐阅读