从电子网络视图中获取选定的文本

2022-01-10 00:00:00 electron javascript angular webview

如何从电子应用程序的 web 视图中获取选定的文本?我正在使用 Angular 和 Electron.所以我有一个有 webview 的组件:

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);

问题:window.getSelection().toString() 不适用于 web 视图中的选定文本.它仅适用于 webview 之外的文本.

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

推荐答案

webView 是 Electron 中的一种特殊标签.作为文档(https://electronjs.org/docs/api/webview-tag) 说,与 iframe 不同,webview 在与您的应用程序不同的进程中运行.它与您的网页没有相同的权限,并且您的应用与嵌入内容之间的所有交互都是异步的..

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

由于它是不同的过程并且不允许直接交互,因此您可以在 webview 和外框之间使用 ipc 进行通信.检查 Electron 的 ipc 是否建立.具体来说,您可能对渲染器主机和 web 视图的 ipcRenderer.sendToHost 感兴趣.

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.

相关文章