Javascript Electron https,node-fetch module not found

brc7rcf0  于 2023-04-11  发布在  Node.js
关注(0)|答案(1)|浏览(158)

下面是我的gate.html代码:

<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self <' https://example.com.tr/validkeys.txt">
    <meta http-equiv='Content-Security-Policy' content="default-src 'self'; script-src 'self'">
    <title>License Gate</title>
    <link rel='stylesheet' href='./index.css'>
  </head>
  <body>
    <form id='license-gate'>
      <label for='key'>
        Please enter your license key
      </label>
      <input id='key' type='text' placeholder='Your license key'>
      <button type='submit'>
        Submit
      </button>
    </form>
  </body>
</html>

这是我的gate.js代码(我在打开gate.html时预加载了它,请参阅我的main.js)

const { ipcRenderer } = require('electron')
const https = require('https')

window.addEventListener('DOMContentLoaded', async () => {
  console.log('DOM content loaded')
  const gate = document.getElementById('license-gate')

  gate.addEventListener('submit', async event => {
    console.log('Submit button clicked')
    event.preventDefault()
    
    const key = document.getElementById('key').value;
    console.log('Entered key:', key)

    https.get('https://example.com.tr/validkeys.txt', (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        const keys = data.trim().split('\n')
        console.log('Valid keys:', keys)

        if (keys.includes(key)) {
          console.log('Key is valid')
          ipcRenderer.send('key-validation-result', true)
        } else {
          console.log('Key is invalid')
          ipcRenderer.send('key-validation-result', false)
        }
      });
    }).on('error', (err) => {
      console.log('Error: ', err.message);
    });
  })
})

我的main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const isDev = process.env.NODE_ENV === 'development'
const { ipcRenderer } = require('electron');

let mainWindow;

async function gateCreateWindowWithLicense(createWindow) { 
  const gateWindow = new BrowserWindow({
    resizable: false,
    frame: false,
    width: 1920,
    height: 1080,
    webPreferences: {
      preload: path.join(__dirname, 'gate.js'), //here, I'm preloading gate.js
      devTools: true,
    },
  })
  
 
  gateWindow.loadFile('gate.html')
 
  if (isDev) {
    gateWindow.webContents.openDevTools({ mode: 'detach' })
  }
   //ipcmain
  ipcMain.on('key-validation-result', async (event, isValid) => {
    if (isValid) {
      // Close the license gate window
      gateWindow.close()
  
      // Launch our main window
      createWindow()
    } else {
      // Show an error message
      const dialogOptions = {
        type: 'error',
        title: 'Invalid license key',
        message: 'The license key you entered is not valid. Please try again.',
        buttons: ['OK'],
        defaultId: 0,
        cancelId: 0,
      }
  
      await dialog.showMessageBox(dialogOptions, gateWindow)
    }
  })
} 

function createWindow() {
  const { screen } = require('electron');
  let factor = screen.getPrimaryDisplay().scaleFactor;
  // get the size of the screen
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;

  mainWindow = new BrowserWindow({
    width: 800/factor,
    height: 600/factor,
    useContentSize: true,
    webPreferences: {
      nodeIntegration: true,
      zoomFactor: 1.0 / factor,
      blinkFeatures: 'OverlayScrollbars'
    },
    autoHideMenuBar: true,
    fullscreenable: true,
  });
  // Update the title of the Electron app window when the website updates its title
  mainWindow.webContents.on('page-title-updated', (event, title) => {
    event.preventDefault();
    mainWindow.setTitle('Axiswiwo');
    
  });
  mainWindow.loadURL("http://www.thewebsitethatiwanttoopen.com/");
  mainWindow.on('closed', function () {
    mainWindow = null;
    
  });
  mainWindow.on('enter-full-screen', () => {
    mainWindow.setResizable(true); // set window to resizable in fullscreen mode
    mainWindow.maximize(); // maximize the window to fill the screen
  });
  mainWindow.on('leave-full-screen', () => {
    mainWindow.setResizable(true); // set window to resizable
    mainWindow.unmaximize(); // restore the window to its previous size
    mainWindow.setSize(800, 600); // resize the window to 800x600
    mainWindow.setAspectRatio(800 / 600);
  });

  // when the window is small, maximize it to fill the screen
  if (mainWindow.isMaximizable()) {
    mainWindow.maximize();
  }
} // end of createwindow

app.whenReady().then(() => {
  gateCreateWindowWithLicense(createWindow);
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow();
  }
});

所以,当我打开程序,在开发工具控制台它说:Dev tools console error
因此,它也无法预加载gate.js。
我试着更新npm,安装“https”,即使它已经在node.js中可用。也找不到“node-fetch”。同样的错误发生。我无法使用XmlHttpRequest,因为它违反了内容策略,我现在无法访问网站面板。window.fetch也无法获取数据。我如何获取这些数据真的不知道。

u5rb5r59

u5rb5r591#

好吧,这是我的错。Electron不允许将大多数节点模块导入到预加载脚本中。请在此处查看更多细节:https://www.electronjs.org/docs/latest/tutorial/tutorial-preload
BrowserWindow的预加载脚本在可以访问HTML DOM以及Node.js和Electron API的有限子集的上下文中运行。
这是它说什么。

相关问题