Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以使用javascript在两个本地html文件之间进行通信吗?_Javascript_Html_Cross Domain - Fatal编程技术网

我可以使用javascript在两个本地html文件之间进行通信吗?

我可以使用javascript在两个本地html文件之间进行通信吗?,javascript,html,cross-domain,Javascript,Html,Cross Domain,我在同一个文件夹中有两个本地.html文件。一个页面与另一个页面一起打开一个窗口,并尝试在新打开的窗口中调用函数。但是,函数调用失败,我在控制台中看到: 不安全的JavaScript试图从URL文件为///***/B.html的框架访问URL文件为///***/A.html的框架。域、协议和端口必须匹配 这在Chrome和Webkit(Mac)上都会发生。是否有任何方法可以:禁用文件://协议的跨域检查,或在其他本地文件中调用javascript函数?您可以使用window.postMessag

我在同一个文件夹中有两个本地.html文件。一个页面与另一个页面一起打开一个窗口,并尝试在新打开的窗口中调用函数。但是,函数调用失败,我在控制台中看到:

不安全的JavaScript试图从URL文件为///***/B.html的框架访问URL文件为///***/A.html的框架。域、协议和端口必须匹配


这在Chrome和Webkit(Mac)上都会发生。是否有任何方法可以:禁用文件://协议的跨域检查,或在其他本地文件中调用javascript函数?

您可以使用window.postMessage执行以下操作:

初始窗口html文件:

<!DOCTYPE html>
<html>
    <head>
        <script>
            var otherWindow;
            function openOther() {
                otherWindow = window.open("other.html", "otherWindow");

            }

            function otherFunc() {
                otherWindow.postMessage("otherFunc", "*");
            }
        </script>
    </head>
    <body>
        <div onclick="openOther()">Open the other window</div>
        <div onclick="otherFunc()">Call the other window's function</div>
    </body>
</html>

var其他窗口;
函数openOther(){
otherWindow=window.open(“other.html”、“otherWindow”);
}
函数otherFunc(){
otherWindow.postMessage(“otherFunc”,“*”);
}
打开另一个窗口
调用另一个窗口的函数
第二个窗口的Html:

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.addEventListener("message", function(event) {
                alert("The other window's function executed.");
            }, false);
        </script>
    </head>
    <body>
        <div>This is the other window.</div>
    </body>
</html>

window.addEventListener(“消息”,函数(事件){
警报(“其他窗口的功能已执行”);
},假);
这是另一个窗口。

这里有一个很好的参考。

您可以运行一个小型静态Web服务器吗?这在Go或Node.js中是微不足道的,我可以,但我真的希望能够双击.html文件。我目前正在我的主服务器上使用VirtualHost。还应该注意的是,有充分的理由为跨域调用提供保护。此解决方案通过在window.postMessage()中传递“*”作为第二个参数来禁用源代码检查,但您确实应该在侦听器函数中通过某种检查来利用此机制。我完全忘记了postMessage!这非常有帮助。太棒了,很高兴它很有用。是否可以在一个html/窗口中将所选文件发送到另一个窗口?我尝试了两种方法,但IE让我紧张不安我知道没有办法直接发送文件,但您可以将其转换为文本并通过PostMessage()发送,保存到可在windows之间访问的本地存储,或者如果不可行,则使用服务器直接中继文件数据。我还可以想到一些其他的机制,你也可以利用它们。我发现,几乎总有一种方法可以实现你的目标,即使技术不配合。祝你好运