以编程方式更改 Electron 中 Webview 的内容
Programmatically Changing the Contents of a Webview in Electron
因此,在我的电子应用程序中,我有一个带有侧边栏(包含一些链接)的主页,然后是一个 webview 占据了大部分页面。我在单独的 .html 文件中有一些页面,我希望能够以编程方式加载到 webview 中。使用 iFrame 就像设置 iframe 的名称属性(比如 "content_frame")然后让我的链接像这样一样简单:
<a id="page1_link" href="pages/page1.html" target="content_frame">page 1</a>
这是我的网页视图:
<webview nodeintegration="on" src="pages/landing_page.html" name="content_frame" height="100%" width="100%"></webview>
第一页 (landing_page.html) 显示正常,但是如果我尝试以相同的方式使用 webview,它将在弹出窗口中打开页面 window,而不是在这个嵌入式网络视图。到目前为止,我一直在为此使用 iframe,但我需要使用来自 electron 的节点内容(来自 iframe 的要求会破坏一切)。
使用锚标记的 target 属性似乎没有一种干净的方法来做到这一点。使用一些 JavaScript,您可以捕获锚点的点击事件并在 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);
});
}
}
});
但是,您必须根据此处的文档提供协议: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://.
因此,在我的电子应用程序中,我有一个带有侧边栏(包含一些链接)的主页,然后是一个 webview 占据了大部分页面。我在单独的 .html 文件中有一些页面,我希望能够以编程方式加载到 webview 中。使用 iFrame 就像设置 iframe 的名称属性(比如 "content_frame")然后让我的链接像这样一样简单:
<a id="page1_link" href="pages/page1.html" target="content_frame">page 1</a>
这是我的网页视图:
<webview nodeintegration="on" src="pages/landing_page.html" name="content_frame" height="100%" width="100%"></webview>
第一页 (landing_page.html) 显示正常,但是如果我尝试以相同的方式使用 webview,它将在弹出窗口中打开页面 window,而不是在这个嵌入式网络视图。到目前为止,我一直在为此使用 iframe,但我需要使用来自 electron 的节点内容(来自 iframe 的要求会破坏一切)。
使用锚标记的 target 属性似乎没有一种干净的方法来做到这一点。使用一些 JavaScript,您可以捕获锚点的点击事件并在 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);
});
}
}
});
但是,您必须根据此处的文档提供协议: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://.