Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to programmatically access the contents of external scripts from an HTML script tag?

Lets say I am using the turndown Javascript package:

https://github.com/mixmark-io/turndown

and loading it this way in my HTML:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script src="https://unpkg.com/turndown/dist/turndown.js"></script>

This loads the following:

enter image description here

and makes TurnDown service available to be used as such:

var turndownService = new TurndownService({ headingStyle: 'atx', emDelimiter : '*' });

Is it possible to programmatically access the contents of such external scripts which has been loaded by the above script tag? Aka, is it possible to get the following:

var TurndownService = (function () {
  'use strict';

  function extend (destination) { ........

  .....

  return TurndownService;

}());

NOTE that I am asking for external scripts. I already know I can get contents of my own script by assigning the tag an id and then using innerHTML on it as such:

Get content inside script as text

The reason I need to do this is that I want to pass these third party scripts to a WebView in iOS using webkit handlers.

>Solution :

Yes! There is a document.scripts property that contains all scripts loaded on a page. However, external scripts loaded with src attribute won’t have innerHTML or textContent, so we will have to fetch it again.

In your case, you can get the contents like this:

const desiredUrl = "https://unpkg.com/turndown/dist/turndown.js"
const script = [...document.scripts].find(script => script.src === desiredUrl)

const url = script.src
const source = fetch(url).then(res => res.text()).then(source => {
  console.log(source.slice(0, 200)) // truncated not to spam console
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading