【问题标题】:Error when loading an external URL in an iframe with Electron使用 Electron 在 iframe 中加载外部 URL 时出错
【发布时间】:2021-10-12 13:29:20
【问题描述】:

我正在尝试使用 Electron 创建一个桌面应用程序,但我无法在 iframe 中加载像 google.com 这样的外部 URL。

下面的代码,在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>

错误:

  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

是什么导致了这个问题,我该如何解决?

【问题讨论】:

标签: iframe electron


【解决方案1】:

补充 Sjoerd Dal 已经回答的内容。

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

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

  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);

【讨论】:

  • 为什么使用 urls[] 而不是 url ?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    相关资源
    最近更新 更多