简体   繁体   English

电子executeJavascript内部未定义的变量

[英]variable undefined inside electron executeJavascript

I am trying out the Electron framework. 我正在尝试Electron框架。 I was trying to scrap the mainWindow then put the returned result in another window. 我试图刮除mainWindow,然后将返回的结果放在另一个窗口中。 I am using the below code(excluding unnecessary codes such as window initialization) 我正在使用以下代码(不包括不必要的代码,例如窗口初始化)

contents = mainWindow.webContents  
contents.on('dom-ready', analyze)
function analyze() {
  contents.executeJavaScript('scrap()').then((result) => {
    message = result.join('\n')
    console.log(message)
    notify_window.webContents.openDevTools()
    notify_window.webContents.executeJavaScript("console.log('test');$('#html').html(message);")
  })
}

Problem is, it is very inconsistence. 问题是,这非常不一致。

1.Sometime it executes the line having notify_window.webContents.executeJavaScript , and sometime it does not. 1.Sometime它执行具有线notify_window.webContents.executeJavaScript ,有时候没有。 When it executes that line, it prints test in window console and below that, shows an error that message is undefined . 当执行该行时,它将在窗口控制台中打印test ,并在其下方显示错误message is undefinedmessage is undefined I can see the value of message every time in electron console from the line console.log(message) so I don't understand why message is undefined when I try to put it in a element. 我每次都可以从console.log(message)行中的电子控制台中看到message的值,因此当我尝试将message放入元素中时,我不明白为什么未定义message

  1. Sometimes It does not execute notify_window.webContents.executeJavaScript , that means I don't see any console statement or error in notify_window but at that time it executes all other lines inside that function since I see the log in electron and it opens the DevTools. 有时,它不执行notify_window.webContents.executeJavaScript ,这意味着我在notify_window不到任何控制台语句或错误,但是由于它看到了电子登录并打开了DevTools,因此它执行了该函数内的所有其他行。 What is happening here ? 这是怎么回事?

I am confused if this is how NodeJS works or it is due to the Promise, that first executeJavaScript returns or It is the behavior of Electron ? 如果这是NodeJS的工作方式或者是由于Promise导致的,则我很困惑,首先executeJavaScript返回还是Electron的行为?

You are passing "message" as a variable name in the executeJavascript, not as the variable in your file and that's why it is undefined. 您在executeJavascript中将“消息”作为变量名传递,而不是在文件中作为变量传递,这就是未定义它的原因。

If you want to send the real "message" that you are using, you have to use: 如果要发送正在使用的真实“消息”,则必须使用:

notify_window.webContents.executeJavaScript("console.log('test');$('#html').html('"+message+"');")

The strange behaviour maybe it's caused by Javascript broken after the error, before reporting the error itself. 奇怪的行为可能是由错误后报告错误之前的Java代码损坏引起的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM