z403
z403

Reputation: 67

Access and change the attributes of <script> tag

How can I access and change the attributes of tag, specially the src? something like this maybe:

document.scripts[i].src

of course it does not work! I intend to alter it this way:

document.scripts[i].src += '?ver3'

in a loop for all the script on the page.

Upvotes: 3

Views: 2330

Answers (3)

user882255
user882255

Reputation:

Install httpd (Apache) and PHP. Put into your hosts file (or hosts.txt) this line:

127.0.0.1 example.com

Write an php script named index.php and put it into server directory (/var/www/html or some like this; depends on configuration).

When you load in web browser http://example.com you will be redirected to 127.0.0.1 (your local server) and in PHP this variable $_SERVER["HTTP_HOST"] will be set to example.com.

Get this site (e.g. using cURL), change what you want (using string functions, regex, DOMDocument, SimpleXML, etc.) and send modified content to browser.

That's all. :)

Upvotes: 0

Guffa
Guffa

Reputation: 700592

You could use document.getElementsByTagName('script') to get all the script elements in the page.

However, any script elements that you find will already have loaded their content, so it will be too late to change the URL that they use to load content.

If you want to alter the URLs, you should use a solution on the server side, so that the URLs are changed when they arrive to the browser.

Upvotes: 4

J0HN
J0HN

Reputation: 26951

With jQuery:

jQuery("script").each(function(){
    var old_src = jQuery(this).attr('src');
    jQuery(this).attr('src', old_src+'?ver3');
})

With good-old JS:

var scripts = document.getElementsByTagName('script');
for (var i=0; i<scripts.length; i++){
    var old_src = scripts[i].getAttribute('src');
    scripts[i].setAttribute('src', old_src +'?ver3');
}

Upvotes: 2

Related Questions