Is it possible to target a div from another html file using JS?

Viewed 300

I have an HTML/JS front-end app connected to a back-end. This application is written by someone else and is stand alone with some continuously updated data. What I wish to do is write a web app that could retrieve some data from this app and display it in my app. Can I target a specific div in the other app in my app and use its content?

2 Answers

Yes!

1. Send a GET request

You should send a GET request from your backend (sorry, you will need one) to the target source to get back the HTML.

2. Mine the div from the response

There are many ways to do so. If you use Javascript, then you could create an invisible div, where you would dump whatever is inside the body tag.

3. Query the div you are interested in

Now their div is in your structure. Query it as you like.

The best way to do this would be to find out what is displaying the text in the div, and use your own API calls to replicate it. I unfortunately can't help you with this because you provided no information regarding the back-end. However, if you need to access the div's content, you can create a hidden iframe loading the necessary HTML, and access the DOM of the iframe.

async function getContentFromHTML(html, id) {
  let frame = document.createElement('iframe');
  document.body.appendChild(frame);
  frame.style.display = 'none';
  frame.src = html;
  let content = await new Promise(function(resolve, _reject) {
    frame.contentWindow.onload = () => resolve(frame.contentDocument.getElementById(id).innerHTML);
  });
  return content;
}

Note that this may allow the other HTML page to access the window of your page, and the HTML page you are trying to load may not be accessible from an iframe, but I won't go into XSS trust here.

Related