sketch-module-web-view icon indicating copy to clipboard operation
sketch-module-web-view copied to clipboard

Get a callback with the result from `sendToWebView`

Open ghost opened this issue 6 years ago • 2 comments

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()?

ghost avatar Oct 27 '19 21:10 ghost

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

scuster1-chwy avatar Dec 11 '19 09:12 scuster1-chwy

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.

mathieudutour avatar Dec 11 '19 09:12 mathieudutour