无法在Electron+Nexjs(Nexon)应用程序的新窗口中打开页面

bkkx9g8r  于 2022-10-21  发布在  Electron
关注(0)|答案(1)|浏览(143)

我尝试在新窗口中打开(Nextjs生成的)页面,但收到以下错误Uncaught ReferenceError: global is not defined
完全错误:

react-refresh.js?ts=1665849319975:10 Uncaught ReferenceError: global is not defined
    at react-refresh.js?ts=1665849319975:10:1
(anonymous) @ react-refresh.js?ts=1665849319975:10
webpack.js?ts=1665849319975:712 Uncaught ReferenceError: global is not defined
    at webpack.js?ts=1665849319975:712:12
    at webpack.js?ts=1665849319975:1209:13
    at webpack.js?ts=1665849319975:1220:12
(anonymous) @ webpack.js?ts=1665849319975:712
(anonymous) @ webpack.js?ts=1665849319975:1209
(anonymous) @ webpack.js?ts=1665849319975:1220
main.js?ts=1665849319975:9 Uncaught ReferenceError: global is not defined
    at main.js?ts=1665849319975:9:1
(anonymous) @ main.js?ts=1665849319975:9
_app.js?ts=1665849319975:9 Uncaught ReferenceError: global is not defined
    at _app.js?ts=1665849319975:9:1
(anonymous) @ _app.js?ts=1665849319975:9
camera.js?ts=1665849319975:9 Uncaught ReferenceError: global is not defined
    at camera.js?ts=1665849319975:9:1

我试过了

import Link from 'next/link'
export default function Item(){
  <Link href="/camera">
    <a target="_blank">
      item
    </a>
  </Link>
}

import Link from 'next/link'
export default function Item(){
  <Link href="/camera">
    <a
      onClick={(e) => {
          window.open(
            "/camera",
            "_blank",
            "top=500,left=200"
          )
        }}>item
    </a>
  </Link>
}

两者都会导致相同的错误。

mi7gmzs6

mi7gmzs61#

这个问题似乎是由contextIsolationnodeIntegration属性引起的。
按照以下方法重写window.open,修复了该问题:

window.open(
            "/camera",
            "_blank",
            "top=500,left=200,contextIsolation=no,nodeIntegration=yes"
            );

为什么?

上下文隔离

上下文隔离是一种确保预加载脚本和Electron的内部逻辑在单独的上下文中运行的功能,该上下文与您在WebContents中加载的网站相关。
Context Isolation on Electronjs docs
例如,如果您在预加载脚本中设置了window.hello = 'wave',并且启用了上下文隔离,则如果网站尝试访问window.hello,则window.hello将为undefined
因此,新窗口中的global对象将是undefined。设置contextIsolation=no可确保global对象与先前设置的对象相同。

节点集成

节点集成是帮助新窗口访问像__dirname这样的NodeJS属性的一种方法。必须启用此功能。

相关问题