Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when loading an external URL in an iframe with Electron

I am trying to create a desktop application using Electron but I am unable to load an external URL like google.com in an iframe.

The code below, inside index.html, triggers an error.

   <!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>

The error :

  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

What is causing this issue and how can I resolve it?

like image 617
Nilay Singh Avatar asked Feb 07 '18 16:02

Nilay Singh


2 Answers

Adding to what has already been answered by Sjoerd Dal.

  1. Adding External URL using IFRAME : Sites block adding their web pages to any other web page, for avoiding click-jacking. This is usually done by :

    a. Adding a response in the header. This stops pages which are not whitelisted/not from same-origin to be included in iframes
    b. Checking if top window is same as current window.

  2. Now to answer your question, there is actually a very easy way to do that:

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);
like image 83
Kaustav Sarkar Avatar answered Oct 24 '22 03:10

Kaustav Sarkar


Most sites these days block other people from iframing them. As you can see with this error, the site only allows iframes coming from the same domain. As an alternative you can use Electron's webview tag which starts the website on a separate thread, sandboxed in its own BrowserWindow. https://electronjs.org/docs/api/webview-tag

like image 24
Sjoerd Dal Avatar answered Oct 24 '22 02:10

Sjoerd Dal