【问题标题】:Javascript document not being called from HTML electron app未从 HTML 电子应用程序调用 Javascript 文档
【发布时间】:2019-06-02 00:48:03
【问题描述】:

我有一个我正在开发的电子应用程序,由于某种原因我无法使用我需要的外部 js 文档。

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript" src="./js/renderer.js"></script>
    <script type="text/javascript" src="./xml/xml.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <link rel="stylesheet" href="./css/styles.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>
    <div id="title-bar">
      <div id="titlebar_lblversion"></div>
      <p id="titlebar_btnmin">&ndash;</p>
      <p id="titlebar_btnclose">&times;</p>
    </div>

    <img id="logo" src="assets/images/logo.png" width="300px" height="282px" />

    <nav class="navbar fixed-bottom navbar-dark bg-dark">
      <a id="btnAuthorize" class="navbar-brand" href="#">Sign In</a>
      <a id="btnRefreshToken" class="navbar-brand" href="#"></a>
      <a id="btnUsername" class="navbar-brand" href="#">USERNAME</a>
    </nav>

  </body>
</html>

index.js

const { app, BrowserWindow, autoUpdater } = require("electron");
//const log = require("electron-log");
const ipcMain = require("electron").ipcMain;
const DOMAIN = "myurlhere";
const suffix =
  process.platform === "darwin"
    ? `/RELEASES.json?method=JSON&version=${app.getVersion()}`
    : "";
const os = require("os");
const path = require('path');
const { dialog } = require("electron");
const isDev = require('electron-is-dev');
const log = require('electron-log');
const gotTheLock = app.requestSingleInstanceLock();

//monitor this..purpose is to prevent app from running while installing
//not sure if this will cause future issues or not.
if (require('electron-squirrel-startup')) return app.quit();

//output current environment
log.info("Developer Env: " + isDev);

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let loaderWindow;
let mainWindow;

const createLoader = () => {
  // Create the browser window.
  loaderWindow = new BrowserWindow({
    width: 400,
    height: 400,
    webPreferences: { webSecurity: false, allowRunningInsecureContent: true },
    frame: false,
    resizable: false,
    icon: path.join(__dirname, 'assets/icons/ico/asset_4.ico')
  });

  log.info("loaderWindow created");

  //make app single instance
  if (!gotTheLock) {
    app.quit();
  } else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
      if(loaderWindow) {
        if(loaderWindow.isMinimized()) loaderWindow.restore()
        loaderWindow.focus();
      }
    })
  }

  //console.log("attempting login....");

  // and load the index.html of the app.
  loaderWindow.loadURL(`file:///${__dirname}/loader.html`);
  log.info("Loaded loaderWindow");

  // Open the DevTools.
  //loaderWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  loaderWindow.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    loaderWindow = null;
  });
}

const createMain = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: { webSecurity: false, allowRunningInsecureContent: true, nodeIntegration: true },
    frame: false,
    resizable: false,
    icon: path.join(__dirname, 'assets/icons/ico/asset_4.ico')
  });

  log.info("mainWindow created");

  //make app single instance
  if (!gotTheLock) {
    app.quit();
  } else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
      if(mainWindow) {
        if(mainWindow.isMinimized()) mainWindow.restore()
          mainWindow.focus();
      }
    })
  }

  //console.log("attempting login....");

  // and load the index.html of the app.
  mainWindow.loadURL(`file:///${__dirname}/index.html`);
  log.info("Loaded mainWindow");

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });

  app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })
}


// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", function() {

  //if we are in dev mode we want to skip the updater logic
  if(isDev) {
      ipcMain.on('start-main', function() {
      loaderWindow.close();
      loaderWindow = null;

      //createMain();
    });

    createMain();
  } else {
    createLoader();
  }


  if(isDev) {

  } else {
    loaderWindow.webContents.on("did-finish-load", () => {
      //check for updates
      autoUpdater.setFeedURL({
          url: `${DOMAIN}/launcher/myidhere/${
          process.platform
          }/${process.arch}${suffix}`,
          serverType: "json"
        }); 

        autoUpdater.checkForUpdates();

        autoUpdater.on("checking-for-update", () => {
          log.info("checking for update in indexjs");
          loaderWindow.webContents.send('update-check');
          console.log("Checking for update in indexjs");
        });

        autoUpdater.on('update-available', () => {
          log.info("update available!");
          loaderWindow.webContents.send('update-available');

          autoUpdater.on('update-downloaded', function (event,releaseName) {
              // # restart app, then update will be applied
              log.info("update downloaded!");
              loaderWindow.webContents.send('update-dl');
              ipcMain.on('update-install', function(event, arg) {
                autoUpdater.quitAndInstall();
              });
          });

        });

        autoUpdater.on("update-not-available", info => {
          log.info("update not available");
          loaderWindow.webContents.send("update-not-available");
          updateNotAvail = true;
        });

        autoUpdater.on("error", error => {
          log.error("AutoUpdater Error: ");
          log.error(error.message);
          log.error(error.stack);
          console.log(dialog.showErrorBox("Error!", error.message));
        });
    });
  }

  app.on("activate", () => {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if(mainWindow === null) {
      createMain();
    }
  });

});

xml.js

const log = require('electron-log');
var md5 = require('md5');

alert('XMLJS');
log.error("XMLJS");

从上面的&lt;head&gt; 部分您可以看到我正在调用 xml.js,但是在我的 xml js 中,它只有“alert("IT WORKS");"什么都没有被调用。同样奇怪的是 renderer.js 工作得很好。任何帮助表示赞赏。谢谢。

【问题讨论】:

  • 请显示工作 js 的代码。 nodeIntegration 是否设置为 true?您是否在 DevTools 控制台中看到错误?
  • nodeintegration 设置为 true。 indexjs 刚刚发布
  • 我指的是renderer.js,你说它很好用。另请检查 DevTools 控制台。
  • 啊,是的,渲染器工作正常。开发控制台中没有列出任何错误。只记录即时打印的消息。

标签: javascript html electron


【解决方案1】:

在您的xml.js 中,尝试使用onload 处理程序调用操作。例如,将所有内容放入方法 init 并这样调用它:

window.addEventListener("load", init);

^ 将该代码放在xml.js 文件的顶部或底部。与window.onload 相比,使用它的优势在于它不会干扰现有的onload 处理程序。

【讨论】:

  • @IgnitionK6 嗯。 xml.js 文件是否实际加载?控制台有错误吗?
  • 实际上设法使用下面 xml.js 中发布的解决方案来修复它。显然我不需要调用我以前调用的任何变量(即 ipc、app、remote 等)。这导致它吓坏了。
  • @IgnitionK6 很高兴听到它已排序:)
【解决方案2】:

解决方案是不要重新定义已在 renderer.js 中定义的变量。这是我的新 xml.js 文件:

xml.js

//this is a placeholder for where the xml comparison will happen between
//the CDN and local files
const electron = require("electron");
const ipc = require('electron').ipcRenderer;
const { dialog } = require("electron");
var md5 = require('md5');

document.addEventListener("DOMContentLoaded", pageLoaded);

function pageLoaded() {
    alert('XMLJS');
    log.error("XMLJS");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2023-01-24
    • 2021-11-11
    • 2019-01-29
    相关资源
    最近更新 更多