电子打开外部网址

Nil*_*ngh 7 electron

我正在尝试使用电子创建桌面应用程序,但我无法加载任何外部 url,如 google.com 或任何东西。

当我在 index.html 中使用此代码时:

   <!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <title>Hello World!</title>
    </head>
    <body>
      <h1>Hello World!</h1>
      <!-- All of the Node.js APIs are available in this renderer process. -->
      <iframe src="http://www.w3schools.com"></iframe>


      <script>
        // You can also require other files to run in this process
        require('./renderer.js')
      </script>
    </body>
  </html>
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

  index.html:1 Refused to display 'https://www.w3schools.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
  www.w3schools.com/ Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE
Run Code Online (Sandbox Code Playgroud)

我的问题是我可以打开 atom 内的任何 url 如果是,那么当我将它作为桌面应用程序或 android 应用程序时它会起作用吗

Kau*_*kar 7

添加到 Sjoerd Dal 已经回答的内容。

  1. 使用 IFRAME 添加外部 URL:站点阻止将其网页添加到任何其他网页,以避免点击劫持。这通常通过以下方式完成:

    一种。在标题中添加响应。这会阻止未列入白名单/非同源的页面包含在 iframe
    b 中。检查顶部窗口是否与当前窗口相同。

  2. 现在回答你的问题,实际上有一个非常简单的方法来做到这一点:

const urls = [
    "https://www.google.com"
]

const createWindow = () =>{
    win = new BrowserWindow({
        center: true,
        resizable: true,
        webPreferences:{
            nodeIntegration: false,
            show: false
        }
    });
    win.maximize();
    win.webContents.openDevTools();
    //win.webContents.
    console.log(urls[0]);

    win.loadURL(urls[0]);
    // win.loadURL(url.format({
    //     pathname: path.join(__dirname,"index.html"),
    //     protocol: 'file',
    //     slashes: true
    // }));
    win.once('ready-to-show',()=>{
        win.show()
    });

    win.on('closed',()=>{
        win = null;
    });
}

app.on('ready', createWindow);
Run Code Online (Sandbox Code Playgroud)


Sjo*_*Dal 4

如今,大多数网站都会阻止其他人对它们进行 iframe。正如您在该错误中看到的,该网站仅允许来自同一域的 iframe。作为替代方案,您可以使用 Electron 的 webview 标签,该标签在单独的线程上启动网站,并在其自己的 BrowserWindow 中沙箱化。https:// Electronjs.org/docs/api/webview-tag