【问题标题】:How do i pass javascript variables to electron and manipulate it我如何将javascript变量传递给电子并对其进行操作
【发布时间】:2019-03-02 02:42:24
【问题描述】:

您好,我是electron 的新手,请多多包涵。

我有这样的情况:

  1. 我将从li获取文件名

  2. 一旦filename 得到我想用下面的代码写它

    var fs = require('fs');
    fs.writeFile('gotfromjsvariable', 'Hello content!', function (err) 
    

    { if (err) 抛出错误; console.log('已保存!'); });

假设 gotfromjsvariable 来自下面的代码

问题是,我如何将它传递给电子 main.js 或同一个文件 node.js

$(document).on('click','#files li',function(){
   var gotfromjsvariable = $(this).data('filename');
   // gotfromjsvariable has to be sent a filename to nodejs or electron
   
   /*
  
 var fs = require('fs');
fs.writeFile('gotfromjsvariable', 'Hello content!', function (err) {
            if (err) throw err;
              console.log('Saved!');
  });
   
   */
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="files">
  <li data-filename="abc.json">abc.json</li>
  <li data-filename="pqr.json">pqr.json</li>
</ul>

【问题讨论】:

  • gotfromjsvariable 是一个变量名。因此,您可以在 fs.writeFile() 方法上使用它而无需单引号

标签: javascript node.js electron


【解决方案1】:

基本上你通过ipcRenderer将消息(数据)从渲染器进程发送到主进程。

但是,由于渲染器进程也可以访问节点 API,因此您的任务可以完全在 html 中完成。您的固定代码可能如下所示:

<!DOCTYPE html>
  <html>
    <body>
      <ul id="files">
        <li data-filename="abc.json">abc.json</li>
        <li data-filename="pqr.json">pqr.json</li>
      </ul>
      <script>
        const fs = require('fs')
        window.$ = window.jQuery = require('jquery')
        $(document).on('click','#files', (e) => {
          var gotfromjsvariable = $(e.target).data('filename')
          fs.writeFile(gotfromjsvariable, 'Hello content!', (err) => {
            if (err) throw err
            console.log('saved')
          })
        })
      </script>
    </body>
 </html>

对于 jquery,我使用了这种方法:https://stackoverflow.com/a/32621989/2550156

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2022-12-14
    • 2018-01-28
    • 2015-04-19
    • 2011-04-04
    • 2014-06-09
    相关资源
    最近更新 更多