問題描述
如何從電子應用程序的 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.
這篇關于從電子網絡視圖中獲取選定的文本的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!