javascript - Electron 没有从 window.open() 返回正确的值

标签 javascript electron

我有一个 Electron 应用程序,它呈现一个 HTML 文件,其内容如下:

<html>
  <head>
    <script>
      var myfunc = function() {
        var data = "Some stuff to display in another window.";
        var secondWindow = window.open();
        secondWindow.document.write(data);
      };
    </script>
  </head>
  <body>
    <button onclick="myfunc();">Open Second Window</button>
  </body>
</html>

现在,这在我的普通浏览器(Firefox)中有效,但在 Electron 应用程序中,当我 JSON.stringify(secondWindow); 时,我得到 {'lined': false}而不是实际的窗口句柄(尽管确实打开了一个空窗口)。

任何人都可以进一步阐明这种行为,或许还有一种使用 Electron 实现预期结果的方法吗?

Electron 应用程序:

const {app, BrowserWindow} = require("electron");
const path = require("path");
const url = require("url");

let win

function createWindow () {
  win = new BrowserWindow({width: 800, height: 600})
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
  win.webContents.openDevTools({"detach": true})
  win.on('closed', () => {
    win = null
  })
}

app.on('ready', createWindow)

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

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

最佳答案

您必须创建BrowserWindow并调用loadURL方法

// In the main process.
const {BrowserWindow} = require('electron')

// Or use `remote` from the renderer process.
// const {BrowserWindow} = require('electron').remote

let win = new BrowserWindow({width: 800, height: 600})
win.on('closed', () => {
  win = null
})

// Load a remote URL
win.loadURL('https://github.com')

// Or load a local HTML file
win.loadURL(`file://${__dirname}/app/index.html`)

更新 请在主 Controller 上处理点击事件:

var remote = require('electron').remote;
$(document).on('click', '#btn', function() {
    // Hide current window
    var currWindow = remote.getCurrentWindow();
    currWindow.hide();
});

处理主窗口隐藏事件以确保主窗口关闭

win.on('hide', function(e) {
    showNewWindow();
});


var showNewWindow = function() {
    newWindow = new BrowserWindow(windowOption);
    newWindow .loadURL(`file://${__dirname}/app/new.html`)
}

关于javascript - Electron 没有从 window.open() 返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44234579/

相关文章:

electron - 如何从 webview 本身更改屏幕大小?

node.js - 从 Electron App 隐藏其他窗口/程序

javascript - 为什么对 html 属性使用变量?

javascript - 使用自调用匿名函数和 $(document).ready

javascript - iOS 9.3 禁用 iPhone 后退按钮上的后退缓存

javascript - Electron - 仅在主窗口上显示菜单

javascript - 为什么 Bootstrap 模态背景滞后?

javascript - 如何仅选择不带 `#` 的链接?

javascript - 在 Electron 中处理表单的正确方法是什么?

javascript - 类型错误 : is not a constructor