Reputation: 656
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.
Upvotes: 1
Views: 805
Reputation: 656
I finally found a solution to this particular issue: Window.postMessage. This is an HTML5 technology that allows for message passing between separate windows with cross-origins, including iframes. Amazingly it works fine with the "file" protocol (ie. no webserver), so it works great for iframes in Electron.
Here is a working example. I have two files: parent.html and child.html. The former has an iframe that contains the latter:
parent.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>
Upvotes: 1