【问题标题】:Manipulate the DOM of an external website in electron在 electron 中操作外部网站的 DOM
【发布时间】:2020-03-21 14:05:26
【问题描述】:

我对电子很陌生。我想加载一个 URL,然后运行一些 Javascript 来操作 DOM。

我目前非常简单地创建一个加载 URL 的 BrowserWindow,并且知道我可以使用 webContents.executeJavascript() 来传递将要运行的 Javascript 字符串。

但是,我希望运行 setInterval(),并传入一个函数,该函数将每隔 x 秒检查并可能操作 DOM。执行此操作的所有代码当前都在一个单独的文件中。

我该怎么做?

【问题讨论】:

    标签: javascript node.js electron


    【解决方案1】:

    您可以通过 script tag 将 JavaScript 文件添加到您的 HTML 中,就像任何 HTML 网站一样:<script type="text/javascript" src="file.js"></script>

    如果您想从主进程发送一个事件作为触发器,请使用webContents of the window。这将向该窗口的ipcRenderer 发送一个事件:

    let mainWindow
    
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
    
    app.whenReady().then(createWindow)
    
    data = true // set any data you need for the trigger
    
    mainWindow.webContents.send('trigger', data)
    

    然后在你添加到 HTML 文件的脚本中处理事件:

    const { ipcRenderer } = require('electron')
    
    ipcRenderer.on('trigger', (event, data) => {
      yourFunction(data)
    })
    

    【讨论】:

      【解决方案2】:

      在 webPreferences 中使用预加载。例如: 加载 google.com 在 main.js 中

      let googleWindow;
      
      // handle create googleWindow
      function createGoogleWindow(){
          googleWindow = new BrowserWindow({
              webPreferences: {
                  nodeIntegration: true,
                  preload:`${__dirname}/scripts/googleWindow.js`
                }});
          //load html into window
          googleWindow.loadURL('https://www.google.com/');
          //garbage collection handle
          googleWindow.on('close', function(){
              googleWindow=null;
          });
      }
      

      上面引用的脚本 googleWindow.js:

      const electron = require('electron');
      function search(){
          const input = document.querySelector('input[name="q"]');
          input.value = "test";
      }
      
      setTimeout(function(){ alert("Hello");search(); }, 3000);
      

      上述脚本在 3 秒后提示“Hello”,并在 google.com 的搜索框中输入“test”。

      您还可以从主进程发送一个事件作为触发器,使用 Melvin Witte 指出的窗口的 webContents。

      【讨论】:

        猜你喜欢
        • 2016-12-02
        • 1970-01-01
        • 2015-06-09
        • 2014-06-07
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多