loading...

iframes everywhere

karataev profile image Eugene Karataev Updated on ใƒป2 min read

How many times you were on a random website and wanted to watch your favorite youtube video right on the current website? I guess it never happened ๐Ÿ˜€. You just opened a new tab and entered youtube in the browser's url input.

But recently I developed chrome extension and faced a problem with injection 3rd websites via iframe in a currently opened website.

Open your browser's dev tools and execute the following code:

(function injectIframe(src) {
  let iframe = document.createElement('iframe');
  iframe.setAttribute('src', src);
  iframe.style.width = '500px';
  iframe.style.height = '300px';
  document.body.prepend(iframe);
})('https://youtube.com');

Your attempt will fail with the message
Refused to display 'https://www.youtube.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

fail

This happens because youtube.com sets header X-Frame-Options to sameorigin, which blocks loading the website in iframe. YouTube don't want to show it's content on other websites and it's a reasonable decision.

Browser extension to the rescue

But there is a way to bypass these security restrictions. You'll have to use a browser extension which have much more access to the client-server interactions.
An extension can intercept a server's response, modify it's headers and provide the modified response without limiting headers to the browser.

We're gonna use webRequest API to modify response headers. Here's the extension code:

function stripHeaders(headers) {
  return headers.filter(header => {
    let headerName = header.name.toLowerCase();
    return !(headerName === 'content-security-policy' || headerName === 'x-frame-options');
  })
}

chrome.webRequest.onHeadersReceived.addListener(
  function(details) {
    return {
      responseHeaders: stripHeaders(details.responseHeaders)
    };
  }, {
    urls: ["<all_urls>"]
  }, ["blocking", "responseHeaders"]);

Here is the repo with full extension code if you want to try it by yourself.

And here we go ๐ŸŒŸ
success

P.S. Extensions have super powers compared to a regular javascript in a website's sandbox. Use them wisely and don't install extension you don't trust โ—

Posted on by:

Discussion

pic
Editor guide