How can I access the DOM of a in Electron?

后端 未结 3 1257
盖世英雄少女心
盖世英雄少女心 2020-12-30 10:40

I\'m just getting started with Electron, with prior experience with node-webkit (nw.js).

In nw.js, I was able to create iframes and then access the DOM of said ifram

3条回答
  •  情话喂你
    2020-12-30 11:09

    I dunno who voted to close my question, but I'm glad it didn't go through. Other people have this question elsewhere online too. I also explained what I wanted to achieve, but w/e.


    I ended up using ipc-message. The documentation could use more examples/explanations for the layperson, but hey, I figured it out. My code is here and here, but I will also post examples below should my code disappear for whatever reason.


    This code is in aries.js, and this file is included in the main renderer page, which is 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);
      }
    });
    

    This next bit of code is in browser.js, and this file gets injected into my .

    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);
    });
    

    I haven't found a reliable way to inject jQuery into s, and I probably shouldn't because the page I would be injecting might already have it (in case you're wondering why my main code is jQuery, but there's also regular JavaScript).

提交回复
热议问题