Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get a callback with the result from sendToWebView #131

Open
ghost opened this issue Oct 27, 2019 · 2 comments
Open

Get a callback with the result from sendToWebView #131

ghost opened this issue Oct 27, 2019 · 2 comments

Comments

@ghost
Copy link

ghost commented Oct 27, 2019

Is there any reliable way to call a javascript function on the web view and get a callback with the result after? I don't have access to webContents in my case, because I am communicating with the web view from another command.
I have tried a few things using getWebview() or accessing the thread dictionary directly, but mostly been causing Sketch to crash and still failing to get a response using .then().

Is there any recommended way using sendToWebview()?

@scuster1-chwy
Copy link

scuster1-chwy commented Dec 11, 2019

@kyotoMike Yes, there is. You have to set stuff up on both sides for it though.

my-command.js

// add a handler for a call from web content's javascript
  webContents.on('nativeLog', s => {
    //UI.message(s)
    webContents
      .executeJavaScript(`setRandomNumber(${Math.random()})`, true)
      .then((num) => {
        UI.message(num)
      })
      .catch(console.error)
  })

webview.js - make sure you return a value

// call the wevbiew from the plugin
window.setRandomNumber = (randomNumber) => {
  document.getElementById('answer').innerHTML = 'Random number from the plugin: ' + randomNumber
  window.postMessage('nativeLogRnd', randomNumber)
  // Make sure you are actually returning a value!!!
  return randomNumber;
}

How I figured this out - Electron docs

https://electronjs.org/docs/api/web-contents#contentsexecutejavascriptcode-usergesture

If this answered your question, please consider closing this issue.

@mathieudutour
Copy link
Member

I think @kyotoMike is talking about using the remote API (eg. accessing the webview from another command/plugin) (which I haven't documented yet #115).

sendToWebview doesn't return a promise (as oppose to executeJavaScript) because it indeed crashes Sketch. I haven't found a way to make it work yet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants