question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Node.js code is not running under tabbed pages.

See original GitHub issue

Describe the bug Code under the tab pages that involves node.js are not running.

To Reproduce

See the code section, create a simple app that contains the tab1.html/tab1.js, and run the app

Expected behavior

On page load, I expect to see a series of alerts:

Here

Path to a found JSON file

The content of the JSON file

Please complete the following information

  • OS: [macOS
  • Browser [Safari]
  • electron-tabs version [0.11.0]
  • Electron version [7.1.12]

Code

The tab page: tab1.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="
        default-src 'self' 'unsafe-inline';
        script-src 'self' 'unsafe-inline';
        connect-src *">
        <!-- <meta http-equiv="Content-Security-Policy" content="default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;"> -->
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Transport</title>
    <link rel="stylesheet" href="style.css" type="text/css">
    <script type="text/javascript" src="myscript.js"></script>
</head>

<body onload="OnLoad();">

</body>
</html>

JS for tab1

const Path = require('path')
const fs = require('fs');
const glob = require('glob');


function OnLoad() {
    alert('Here');
    var filePaths = ListDir(__dirname, ".json");
    alert(filePaths.length.toString());
    for(var f=0; f<filePaths.length; f++) {
        alert(filePaths[f]);
        LoadJSON(filePaths[f], function (response) {
            var jsonObj = JSON.parse(response);
            alert(response);
        });
    }
}

function ListDir(rootDir, ext) {
    if (!fs.existsSync(rootDir)) {
        alert("no dir: " + rootDir);
        return [];
    }
    var filePaths = fs.readdirSync(rootDir);
    filePaths = filePaths.filter(file => file.endsWith(ext));
    return filePaths;
};

function LoadJSON(path, callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', path, true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
        }
    };
    xobj.send(null);   
}

The renderer

const { remote, ipcRenderer } = require('electron');
const TabGroup = require("electron-tabs");
const mainProc = remote.require('./main.js'); // plug in main process
const parser = new DOMParser();

let tabGroup = new TabGroup({
    newTab: {
        title: 'New Tab'
    }
});

tabGroup.addTab({
    title: 'Tab 1',
    src: './tab1.html',
    closable: false,
    active: true
});

The main script

const {app, BrowserWindow} = require('electron');

let mainWindow = null;

app.on('ready', () => {
    console.log('Hello from Electron');
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true,
            webviewTag: true
        }
    });

    mainWindow.webContents.loadFile('./app/index.html');

    // mainWindow events, within app lifecycle
    mainWindow.webContents.on('did-fail-load', function() {
        console.log("Failed to load index.html");
    })

})

The index page

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="
        default-src 'self' 'unsafe-inline';
        script-src 'self' 'unsafe-inline';
        connect-src *">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>MAM Hub</title>
    <link rel="stylesheet" href="style.css" type="text/css">
</head>

<body>
    <!-- 2. Include the basic markup of the tabs view -->
    <div class="etabs-tabgroup">
        <div class="etabs-tabs"></div>
        <div class="etabs-buttons"></div>
    </div>
    <div class="etabs-views"></div>
    <!--
        3. Include initialization code, you can include another js file
        Or write directly the JS code here.
    -->
    <script>
        // You can also require other files to run in this process
        require('./renderer.js')
    </script>
</body>

</html>

Observation With the above code, I can see the Alert showing Here only. The subsequent Alerts didn’t show.

Additional Information The same behavior code if run in an Electron renderer.js just works: I am able to see all the Alerts about the found JSON file and its content.

So my guess is that the fs calls under the tab didn’t work. However, there are no errors in the Chromium console.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8

github_iconTop GitHub Comments

3reactions
millimoosecommented, Feb 19, 2020

At a guess you need to enable nodeIntegration when creating the tab:

tabGroup.addTab({
	// etc.
	webviewAttributes: {
		nodeintegration: true
	}
});
2reactions
nitish173commented, Feb 20, 2020

You may additionally need to enable webviewTag (https://www.electronjs.org/docs/api/browser-window) based on electron version you are using, like so:

webPreferences: {
      nodeIntegration: true,
      webviewTag: true,
}

Thanks! webPreferences does not work here. It has to be webviewAttributes.

Did you add nodeintegration to the tag ? I’m looking at the index.js and have no idea where to make the change.

Refer: https://www.npmjs.com/package/electron-tabs#usage

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js calls not working from HTML script under a tabbed view
The app uses electron-tab to implement a tabbed view. Code. The following HTML is the html page loaded from a tab: tab1.html ....
Read more >
Quickstart: Create a Node.js web app - Azure App Service
Install Node.js and npm. Run the command node --version to verify that Node.js is installed. Install Visual Studio Code. The Azure ...
Read more >
JavaScript - Bootstrap
Multiple open modals not supported. Be sure not to open a modal while another is still visible. Showing more than one modal at...
Read more >
Puppeteer not working when is not focused · Issue #3339
Yes, page`s javascript are paused. While window is not focused. I think, this behaviour is related something settings in my operating system.
Read more >
tabs.executeScript() - Mozilla - MDN Web Docs
Injects JavaScript code into a page. ... In Firefox, relative URLs not starting at the extension root are resolved relative to the current ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found