Cannot send a message to dynamically created webview


I’m creating main window

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

with index.html content

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

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';
    // 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

    <script src="webview.js"></script>
    <p>Inside webview.</p>

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

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

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


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', '');


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