2

How to get the selected text from a webview in an electron application? I am using Angular with Electron. So I have a component which has a webview:

<webview id="foo" attr.src={{activeUrl}} style="height: 600px"></webview>

This is what I use for getting the selected text:

let rightClickPosition = null;
const menu = new Menu();
const menuItem = new MenuItem({
  label: 'Get selected text',
  click: () => {
    // does not work for selected text in webview
    console.log(window.getSelection().toString());
  }
});
menu.append(menuItem);
window.addEventListener('contextmenu', (e) => {
  e.preventDefault();
  rightClickPosition = {x: e.x, y: e.y};
  menu.popup(remote.getCurrentWindow());
}, false);

The problem: window.getSelection().toString() does not work for the selected text in the webview. It works only for the text outside the webview.

1 Answer 1

2

webView is special kind of tag in Electron. as document (https://electronjs.org/docs/api/webview-tag) says, Unlike an iframe, the webview runs in a separate process than your app. It doesn't have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous..

Since it's different process and doesn't allow direct interaction, way you can communicate is using ipc between webview and outer frame. Check Electron's ipc to establish. Specifically you may interested in ipcRenderer.sendToHost for renderer host and webview.

3
  • 1
    Thank you! I found a tutorial here: ourcodeworld.com/articles/read/201/…
    – Unknown
    Dec 17, 2017 at 21:00
  • @Mate have you found solution, I didn't see tutorial on how to get selected text, I want to perform "search with google" for selected text.
    – Wasim A.
    Nov 13, 2018 at 12:19
  • 1
    @WasimA. You can use the ipcRenderer.sendtoHost function. Example: ipcRenderer.on('request', function(){ ipcRenderer.sendToHost('selection', window.getSelection().toString()); });
    – Unknown
    Dec 3, 2018 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.