Cannot send a message to dynamically created webview


#1

I’m creating main window

mainWindow = new BrowserWindow({width: 1200, height: 700});
mainWindow.loadUrl('file://' + __dirname + '/index.html');

with index.html content

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
	<script src="index.js"></script>
  </head>
  <body>
    <h1 id="headline">Hello World!</h1>
  </body>
</html>

included this index.js script

document.addEventListener("DOMContentLoaded", function() {
    // create webview
    var webview = document.createElement('webview');
    webview.addEventListener('did-finish-load', onWebViewLoaded);
    webview.src = 'webview.html';
    document.body.appendChild(webview);
	
    // attach handler to click event
    document.getElementById('headline').addEventListener('click', onHeadlineClick);
});

function onWebViewLoaded() {
    this.send('my-message', 'from onWebViewLoaded');
}

function onHeadlineClick() {
    var webview = document.getElementsByTagName('webview')[0];
    webview.send('my-message', 'from onHeadlineClick');
}

where the webview element is dynamically created. Inside 2 event handlers (did-finish-load and click) I send a message to the created webview. The webview.html looks like

<!DOCTYPE HTML>
<html>
<head>
    <title></title>
    <script src="webview.js"></script>
</head>
<body>
    <p>Inside webview.</p>
</body>
</html>

where I’m trying to catch the incoming messages inside the webview.js

require('ipc').on('my-message', function(message) {
    alert(message);
});

but the alert is not called in any of those 2 cases (event handlers). What is wrong?


#2

I solved the problem already. The webview tag have to have nodeintegration attribute to be able calling require('ipc') inside webview. So this line of code is needed in index.js:

webview.setAttribute('nodeintegration', '');

#3

Alternatively, you can put the code requiring require access in a preload script.