Check If a Website Can Be Embedded in an IFrame With Node.js

• 2 min read

I’ve been working on a new project recently that requires previewing external web pages in an iframe. This feature is not always possible though because websites can prevent themselves from showing in iframes by setting the x-frame-options header. Since there is no way to get around this rule, the only option is to detect whether the website sets this rule and show the user something else. The following snippet shows how to check this header from Node.js using the request module:

var request = require('request');

request(url, function(err, response) {
  var isBlocked = 'No';

  // If the page was found...
  if (!err && response.statusCode == 200) {

    // Grab the headers
    var headers = response.headers;

    // Grab the x-frame-options header if it exists
    var xFrameOptions = headers['x-frame-options'] || '';

    // Normalize the header to lowercase
    xFrameOptions = xFrameOptions.toLowerCase();

    // Check if it's set to a blocking option
    if (
      xFrameOptions === 'sameorigin' ||
      xFrameOptions === 'deny'
    ) {
      isBlocked = 'Yes';
    }
  }

  // Print the result
  console.log(isBlocked + ', this page is blocked');
});

While this example uses the request module for brevity, any method of making an external HTTP request could have been used.

Happy coding.

If you enjoyed this tutorial, please consider sponsoring my work on GitHub 🤗

Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 3 min read
🚅 Next Stop, Yaak
Read Post »
• 4 min read
💻 Wait for User to Stop Typing, in JavaScript
Read Post »