dreamer
dreamer

Reputation: 11

How to get text inside script tag html?

I tried to get this link 'video_versions' text from this url https://www.instagram.com/p/Cahc9hbr9Jp/ but it doesn't show anything. Here's my code

  var c = document.createElement("html");
  c.innerHTML = content;
  scripts = c.querySelectorAll('script');
  script = scripts[scripts.length-2];

  console.log(script.innerHTML.split('video_versions').pop());

Upvotes: 1

Views: 1568

Answers (2)

traktor
traktor

Reputation: 19301

Although scriptElement.textContent is perhaps more appropriate than scriptElement.innerHTML both seem to work if they work at all.

However they only retrieve text between the opening and closing <script> tags present in the HTML source, so they are only good for reading the content of inline scripts. The URL posted doesn't strike me as the kind of page with hand-crafted inline scripts.

If you want to read the script text fetched by a script tag with a src attribute specifying its URL, you would need to repeat the fetch process in JavaScript using either the Fetch or XMLHttpRequest API for the same URL. The success of doing so depends on the server's cross origin policy allowing it.

Upvotes: 1

ca1c
ca1c

Reputation: 1295

This is because you aren't getting the innerHTML property of the script element object, you are simply returning the object of the element from the DOM.

try:

script = scripts[scripts.length-2].innerHTML;

Upvotes: 0

Related Questions