Get selected text from electron webview

2019-04-02 10:04发布

问题:

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:

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.