首页 文章

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

提问于
浏览
1

因此,在我的电子应用程序中,我有一个带有侧边栏的主页(包含一些链接),然后是一个占据大部分页面的webview . 我有一些页面在单独的.html文件中,我希望能够以编程方式加载到webview . 使用iFrames就像设置iframe的name属性一样简单(比如说“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,但我需要使用来自电子的节点内容(iframe需要打破所有内容) .

1 回答

  • 1

    使用anchor标记的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

    在webview中加载url,url必须包含协议前缀,例如http://或file:// .

相关问题