Документ Javascript не вызывается из электронного приложения HTML - PullRequest
2 голосов
/ 02 июня 2019

У меня есть электронное приложение, которое я разрабатываю, и по какой-то причине я не могу работать с нужным мне внешним 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");

из раздела <head> над вамивидно, что я вызываю xml.js, однако в моем xml js, который имеет только "alert (" IT WORKS ");"ничего не называется.Что еще странно, так это то, что renderer.js работает просто отлично.Любая помощь приветствуется.Спасибо.

Ответы [ 2 ]

1 голос
/ 02 июня 2019

Решением было не переопределять переменные, которые уже определены в 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");
}
1 голос
/ 02 июня 2019

В вашем xml.js попробуйте вызвать действия с обработчиком onload. Например, поместите все в метод init и вызовите его так:

window.addEventListener("load", init);

^ Поместите этот код вверху или внизу вашего xml.js файла. Преимущество использования этого по сравнению с window.onload заключается в том, что оно не мешает существующим обработчикам onload.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...