简体   繁体   中英

variable undefined inside electron executeJavascript

I am trying out the Electron framework. I was trying to scrap the mainWindow then put the returned result in another window. 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. When it executes that line, it prints test in window console and below that, shows an error that message 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.

  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. 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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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