gpt4 book ai didi

javascript - Electron JS : avoiding cross-origin issues

转载 作者:行者123 更新时间:2023-12-03 12:28:17 25 4
gpt4 key购买 nike

在正常情况下,具有页面间通信的 Web 应用如果它们的页面是从“http”协议(protocol)中的同一个域提供的,则无需担心跨域访问。默认情况下,Electron 似乎通过"file"协议(protocol)使用网页构建应用程序。该协议(protocol)不允许任何页面间通信。

如果我的 Electron 应用程序需要页面间通信(在这种情况下是通过 iframe),我认为该应用程序需要与 Electron 一起运行网络服务器是正确的吗?这似乎太过分了,我还没有看到太多关于它的讨论,但我看不出有什么更好的解决方法。有一个用于自定义协议(protocol)的 Electron API,但文档没有显示如何使用自定义协议(protocol),只是如何设置它们,我还没有找到任何好的教程。

总的来说,ElectronJS 作为一个框架和一个社区给我留下了深刻的印象,所以我很惊讶在经过一番认真的搜索之后我无法找到解决这个问题的方法。我发现这个问题问了很多次,但没有可靠的答案。我真的很感激一些启示。

更新:

我现在看到我的情况的细节(需要在父窗口和 iframe 之间进行对话)使这个问题比如果有两个单独的窗口(例如主窗口和设置窗口)作为主进程通常可以做的更棘手通过 IPC 充当联络人。这无疑解释了为什么解决方案如此难以捉摸。

最佳答案

我终于找到了解决这个特定问题的方法: Window.postMessage .这是一种 HTML5 技术,允许在跨域的不同窗口之间传递消息,包括 iframe。令人惊讶的是,它适用于"file"协议(protocol)(即没有网络服务器),因此它适用于 Electron 中的 iframe。

这是一个工作示例。我有两个文件:parent.html 和 child.html。前者有一个包含后者的 iframe:

父.html

<html>
<body>
<iframe id='f' src='child.html'></iframe><br/> <!-- First of two differences -->
<button id='b'>send</button><br/>
<div id='o'></div>
</body>
</html>
<script>
function receiveMessage(evt)
{
document.getElementById('o').innerHTML += evt.data + "<br/>";
}
window.addEventListener("message", receiveMessage, false);

document.getElementById('b').onclick = function()
{
// The second of two differences between parent and child is below
document.getElementById('f').contentWindow.postMessage("parent to child", "*");
}
</script>


child.html

<html>
<body>
<!-- The first of two differences between parent and child is here -->
<button id='b'>send</button><br/>
<div id='o'></div>
</body>
</html>
<script>
function receiveMessage(evt)
{
document.getElementById('o').innerHTML += evt.data + "<br/>";
}
window.addEventListener("message", receiveMessage, false);

document.getElementById('b').onclick = function()
{
// The second of two differences between parent and child is below
window.parent.postMessage("child to parent", "*");
}
</script>

关于javascript - Electron JS : avoiding cross-origin issues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58156367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com