gpt4 book ai didi

javascript - 以编程方式更改 Electron 中 Webview 的内容

转载 作者:行者123 更新时间:2023-11-28 01:14:09 27 4
gpt4 key购买 nike

所以在我的 electron 应用程序中,我有一个带有侧边栏(包含一些链接)的主页,然后是一个 webview 占据了大部分页面。我在单独的 .html 文件中有一些页面,我希望能够以编程方式加载到 webview 中。使用 iFrame,只需设置 iframe 的名称属性(例如“content_frame”),然后将我的链接设置为如下内容一样简单:

<a id="page1_link" href="pages/page1.html" target="content_frame">page 1</a>

这是我的 WebView :

<webview nodeintegration="on" src="pages/landing_page.html" name="content_frame" height="100%" width="100%"></webview>

第一页 (landing_page.html) 显示正常,但如果我尝试以相同方式使用 webview,它将在弹出窗口中打开页面,而不是在此嵌入式 webview 中。到目前为止,我一直在为此使用 iframe,但我需要使用来自 electron 的节点内容(来自 iframe 的要求会破坏一切)。

最佳答案

使用 anchor 标记的目标属性似乎没有一种干净的方法来做到这一点。使用一些 JavaScript,您可以捕获 anchor 的点击事件并在 webview 上使用 loadURL 来更改页面。肯定有更优雅的方法可以做到这一点,但这是可行的:

var webview = document.getElementsByName('content_frame')[0];
var bound = false;
webview.addEventListener("dom-ready", function() {
if (bound) return;
bound = true;
var anchors = document.getElementsByTagName("a");
for (var a = 0; a < anchors.length; a++) {
var anchor = anchors[a];
if (anchor.getAttribute('target') == 'content_frame') {
anchor.addEventListener('click', function (e) {
e.preventDefault();
webview.loadURL(e.srcElement.href);
});
}
}
});

但是,您必须根据此处的文档提供协议(protocol):http://electron.atom.io/docs/v0.37.4/api/web-view-tag/#webviewloadurlurl-options :

Loads the url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://.

关于javascript - 以编程方式更改 Electron 中 Webview 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36424763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com