首页 > 解决方案 > ElectronJS: avoiding cross-origin issues

问题描述

Under normal circumstances, web apps with inter-page communication don't need to worry about cross-origin access if their pages are served from the same domain in the "http" protocol. Electron seems to build applications using webpages over "file" protocol by default. This protocol does not allow for any inter-page communication.

If my Electron application needs inter-page communication (over an iframe in this case) am I right in thinking that the application needs to run a webserver alongside Electron? It seems excessive and I haven't seen much talk about it, but I can't see any better way around it. There is an Electron API for custom protocols, but the docs don't show how to use custom protocols, just how to set them up and I haven't been able to find any good tutorials on it.

Overall, I've been impressed with ElectronJS as a framework and as a community, so I'm surprised that I've not been able to find a solution to this issue after some serious searching. I've found the question asked a number of times, but no solid answers. I'd really appreciate some enlightenment.

Update:

I see now that the particulars of my situation (needing to talk between a parent window and an iframe) make this a more tricky problem than if there were two separate windows (such as a main window and settings window) as the main process can usually act as a liason through IPC. This certainly explains why a solution has been so elusive.

标签: javascripthtmlelectronwebserver

解决方案


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


推荐阅读