我刚刚开始使用 Electron,之前使用过 node-webkit (nw.js)。
在 nw.js 中,我能够创建 iframe,然后访问所述 iframe 的 DOM,以获取标题、网站图标等内容。几天前当我选择 Electron 将我的 nw.js 应用程序移植到它时,我看到了使用 webview 而不是 iframe 的建议,仅仅是因为它们更好。现在,我上面提到的功能在 nw.js 中相对容易实现,但我不知道如何在 Electron 中实现(而且示例很少甚至没有)。谁能帮忙?
另外,我的 webview 有后退/前进按钮(我打算有多个)。我在文档中看到我可以在 webview 上调用函数来执行此操作,但我尝试过的任何方法都不起作用(而且,我还没有找到它们在野外使用的示例)。
最佳答案
我不知道是谁投票结束了我的问题,但我很高兴它没有通过。其他人在网上其他地方也有这个问题。我还解释了我想要实现的目标,但是 w/e。
我最终使用了 ipc-message
. documentation可以为外行使用更多示例/解释,但是嘿,我想通了。我的密码是 here和 here ,但如果我的代码因任何原因消失,我也会在下面发布示例。
此代码在 aries.js
中,并且此文件包含在主渲染器页面中,即 index.html
.
var ipc = require("ipc");
var webview = document.getElementsByClassName("tabs-pane active")[0];
webview.addEventListener("ipc-message", function (e) {
if (e.channel === "window-data") {
// console.log(e.args[0]);
$(".tab.active .tab-favicon").attr("src", e.args[0].favicon);
$(".tab.active .tab-title").html(e.args[0].title);
$("#url-bar").val(e.args[0].url);
$("#aries-titlebar h1").html("Aries | " + e.args[0].title);
}
// TODO
// Make this better...cancel out setTimeout?
var timer;
if (e.channel === "mouseover-href") {
// console.log(e.args[0]);
$(".linker").html(e.args[0]).stop().addClass("active");
clearTimeout(timer);
timer = setTimeout(function () {
$(".linker").stop().removeClass("active");
}, 1500);
}
});
下一段代码在 browser.js
中, 这个文件被注入(inject)到我的 <webview>
中.
var ipc = require("ipc");
document.addEventListener("mouseover", function (e) {
var hoveredEl = e.target;
if (hoveredEl.tagName !== "A") {
return;
}
ipc.sendToHost("mouseover-href", hoveredEl.href);
});
document.addEventListener("DOMContentLoaded", function () {
var data = {
"title": document.title,
"url": window.location.href,
// need to make my own version, can't rely on Google forever
// maybe have this URL fetcher hosted on hikar.io?
"favicon": "https://www.google.com/s2/favicons?domain=" + window.location.href
};
ipc.sendToHost("window-data", data);
});
我还没有找到将 jQuery 注入(inject) <webview>
的可靠方法s,我可能不应该,因为我要注入(inject)的页面可能已经有了它(如果你想知道为什么我的主要代码是 jQuery,但也有常规的 JavaScript)。
关于javascript - 如何在 Electron 中访问 <webview> 的 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523171/