cryptopi cryptopi - 1 year ago 98
Javascript Question

Use JQuery to Modify external JS File

I don't know if this possible so I apologize in advance if this question comes off as being a little ignorant.
I am working a website that must use a template and server-side languages such as PHP are disallowed. There is an external JS file on the website that I would like to modify but I cannot figure out how to access/modify it from the main script using JQuery.

In case that was not clear, here is an example:

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="fileToModify.js"></script>
<title>Untitled Document</title>
<script src=""></script>
<script>code to modify external file goes here</script>

In the above example, I would like to be able to place code (in JQuery/JS/some other language like that) where it says "code to modify external file goes here" and alter the local copy of "fileToModify.js" (for example, to delete a function within it). I am aware that, if successful, such a deletion could not alter the real file hosted on the server; I am only trying to alter the local copy when the user downloads it to change how it behaves after the page loads).

Would such a task be possible with JQuery/JS/something of the sort?

Thanks for your help

m59 m59
Answer Source

You can use ajax to get the contents of the file (and not execute it), then do use javascript to replace some of the data. Then you could use eval to execute it.

  method: 'GET',
  dataType: 'text',
  url: 'to-modify.js'
}).then(function(data) {
  data = data.replace('bar();', '')

Live demo (click)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download