Search code examples
javascriptiframexmlhttprequest

How to use the XMLHttpRequest api to retrieve the title of the current page loaded in an iframe?


I'm working on a solid-js application that has an iframe containing a site. I am trying to obtain the title of the current page loaded in the iframe and not having the same domain name as my site. I would like to know if it is possible to get this title using the XMLHttpRequest api. Here is the code of my iframe:

<iframe
      width="100%"
      height="1300"
      id="iframeID"
      src="https://gkwhelps.herokuapp.com"
    ></iframe>

Solution

  • It's not possible in front-end JavaScript alone, due to security restrictions - you can't do anything with a document in a different domain unless that domain has specifically set things up to allow you do interact with it, which is quite unusual.

    But it's not impossible. If you set up an app on your own server, you can have your site make a request to your server-side app, and have your app then make a request to the external site, and then either return the text of the response to your client, or parse the response yourself and send the document title to the client.

    For example, in an express server, node-fetch, and JSDom, you could do something like:

    fetch('https://gkwhelps.herokuapp.com')
      .then(res => res.text())
      .then((responseText) => {
        const doc = new JSDOM(responseText);
        res.send(doc.title);
      })
      // .catch(handleErrors);
    

    And then from the client, you just need to make a fetch or an XMLHttpRequest to your app, and the title will be returned.