【问题标题】:Electron - How to pass JSON from main window to remote window?Electron - 如何将 JSON 从主窗口传递到远程窗口?
【发布时间】:2020-09-25 05:05:47
【问题描述】:

我一共处理了 3 个文件。

index.html:

...
<a href="#" onclick="fetch(function(data) {console.log(data); subWindow(data)})">subWindow</a>
...

fetch() 函数返回 JSON 格式的 callback。


subWindows.js:

let micWindow

function subWindow(data) {
    micWindow = new BrowserWindow({
        width: 1280,
        height: 800
    })

    console.log(data)

    micWindow.show()

    micWindow.loadFile('src/subWindow.html')
    micWindow.webContents.on('did-finish-load', function() {
        let javascript = `document.querySelector('body').innerHTML = '` + data + `'`
        micWindow.webContents.executeJavaScript(javascript)
    })
}

最后是subWindow.html,其中包含纯html。它还导入subWindows.js:

...
<!-- JS Imports -->
<script src="js/subWindows.js"></script>
...

首先,index.html 控制台日志在MIC.js?[sm]:10 打印onclick 和subWindow() 的JSON 数据。 subWindow.html 显示来自executeJavascript 的[object Object],但控制台为空。

其次,下面的做法是行不通的:

let javascript = `document.querySelector('body').innerHTML = '` + JSON.stringify(data) + `'`

或

 let javascript = 'console.log(' + data + ')'

两者都在subWindow.html

中抛出异常Uncaught SyntaxError: Unexpected identifier

JSON 数据不是由subWindows.js 在subWindow.html 中呈现,而是在index.html 中呈现:

index.html 导入 &lt;script src="js/subWindows.js"&gt;&lt;/script&gt;


  • 为什么会报错?
  • 如何将 JSON 数据作为函数参数从主窗口传递到远程窗口?

最好将 JSON 传递给 executeJavascript 并将其注入远程窗口的 html。

感谢您的任何反馈!

【问题讨论】:

    标签: javascript html node.js json electron


    【解决方案1】:

    我不确定错误,但我的解决方案是通过编辑 HTML 将数据放入窗口中。这是执行此操作的一种方法:

    // win is the window you are passing info to
    var data = win.document.createElement('span');
    data.innerHTML = json;
    win.document.body.appendChild(data);
    

    窗口中的程序会等待元素出现,然后将值用于函数。

    注意: 我刚刚注意到您的 JavaScript 在行尾没有任何分号。您需要在每个语句之后都有一个。 :)

    【讨论】:

    • 感谢您的回答@mega12345mega,只是为了澄清我没有对您的帖子投反对票。这不是一个有效的解决方案,因为let javascript = "document.querySelector('body').innerHTML = 'TEST'" 在这种情况下确实有效,无论分号如何。 JSON 数据在执行时以某种方式保留在 index.html 中,这解释了为什么 console.log(data)(包括 function subWindow(data){console.log(data)})在 subWindow.html 的控制台为空时打印两次。远程窗口似乎读取[object Object],但将其打印到控制台会导致错误;无需等待元素首先出现。
    • @user13581602 我只是查了一下,如果有换行符显然不需要分号,但这样做是个好习惯。我总是被不同的教导!无论如何,如果出现 [object Object],则 JSON 数据必须在不使用 JSON.stringify(object) 的情况下转换为字符串。尝试在没有 qoutes 的情况下使用它 - 它看起来像您测试的问题let javascript = `document.querySelector('body').innerHTML = '` + JSON.stringify(data) + `'。试试let javascript = document.querySelector('body').innerHTML = JSON.stringify(data)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多