EN VI

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

2024-03-13 02:00:08
Javascript - 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:

<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
})
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login