用程序更改Electron中Web视图的内容

Programmatically Changing the Contents of a Webview in Electron

本文关键字:视图 Web 程序 Electron      更新时间:2023-12-26

所以在我的电子应用程序中,我有一个带有侧边栏(包含一些链接)的主页,然后是一个占据大部分页面的网络视图。我在单独的.html文件中有一些页面,我希望能够以编程方式加载到Web视图中。使用iframe,只需设置iframe的name属性(比如"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)显示得很好,但如果我尝试以同样的方式使用网络视图,它会在弹出窗口中打开页面,而不是在这个嵌入的网络视图中。到目前为止,我一直在使用iframe,但我需要使用电子中的节点内容(iframe的要求会破坏一切)。

使用锚标记的target属性似乎没有一种干净的方法。使用一些JavaScript,您可以捕获锚点的点击事件,并在网络视图中使用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-选项:

在Web视图中加载url,url必须包含协议前缀,例如http://或file://。