【问题标题】:I am not able to access variable 'dps' declare in index.js within index.html , using npm start我无法使用 npm start 访问 index.html 中 index.js 中声明的变量“dps”
【发布时间】:2016-03-07 20:36:22
【问题描述】:

我无法使用 npm start(用于启动电子应用程序)访问 index.html 内 index.js 中声明的变量“dps” 我能够访问我的 sql 并在 index.js 中获取数据,我想在 index.html 上显示它(使用 nodeJs 和 Electron) 'dps'是指有mysql数据的js对象

//我的index.js文件有

var app = require('app'); 
var dps = [{x:1,y:2}];
// Module to create native browser window.
var BrowserWindow = require('browser-window');
var mainWindow = null;
var dps = [{x:1,y:2}];
var mysql = require('mysql');

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function () {

  // Create the browser window.
  mainWindow = new BrowserWindow({ width: 800, height: 600 });
  mainWindow.loadUrl('file://' + __dirname + '/index.html');
  // Open the devtools.
  // mainWindow.openDevTools();
  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});


//My html file

<html>
<head>
<!--<script type="text/javascript" src = "index.js"/>-->
<script type="text/javascript" src="index.js"></script>
    <script type="text/javascript">
  alert(dps); --- not getting dps value here(/anywhere in html)
</head>
</html>

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    您在 index.html 中的代码与您在 index.js 中的代码(在主进程中运行)在不同的进程(通常称为 Renderer 进程)中运行。此外,您的 index.js 文件是一个模块,因此,即使这两个文件由同一个进程运行,您也必须导出您的 dps 变量或使其成为像 global.dps 这样的全局变量(但是,这是一个不好的做法!)。

    有多种方法可以在 Main 和 Renderer 进程之间共享日期; Electron 为此提供了ipcMainipcRendererremote 模块;您还可以使用 URL 编码参数将数据从 Main 传递到 Renderer(但如果数据更改,这对您没有帮助);最后,您可以使用任何其他形式的 IPC(例如,通过套接字发送消息、使用共享内存或共享文件等)——但最好从 Electron 的 ipcremote 模块开始。

    话虽如此,在您的情况下,consensus 似乎不是仅使用 Main 进程进行 DB 访问,然后将信息传递给 Renderer,而是直接从 Renderer 访问 DB;这样你就完全不用担心 IPC(至少在这种情况下)。

    【讨论】:

    • 感谢您的指导伙伴 :)
    猜你喜欢
    • 1970-01-01
    • 2020-01-15
    • 2019-11-21
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多