Get a callback with the result from `sendToWebView`
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()?
@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.
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.