Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace or delete javascript tag for another before load content

I need to replace specific script tag <script> for another script tag <script> before load content html. I mean, I don't want to load this javascript, since it is advertising.

Replace this <script type='text/javascript' src='http://site.net/c/banner_s?tenant=AD&selection=5986&size=728x90&skin=bottom_middle&di=1'></script>

for this <script type='text/javascript' src='http://newsite...'></script>

otherwise remove the tag.

Here is my code, but this deletes all script tags, and i want specific tag (mentioned before)

function stripScripts(s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;
    while (i--) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
    return div.innerHTML;
  }

alert(
 stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')
);

thanks in advance

like image 552
jose sanchez Avatar asked Sep 10 '26 13:09

jose sanchez


2 Answers

How much of the url do you know?

If you know all of it and it won't change:

var scripts = document.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
  if (scripts[i].src === "http://site.net/c/banner_s?tenant=AD&selection=5986&size=728x90&skin=bottom_middle&di=1") {
    srcipts[i].src = newSrc; // Your source here
    break;
  }
}

If you know some of it won't change:

var scripts = document.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
  if (scripts[i].src.indexOf("http://site.net/c/banner_s?...") === 0)  {
    srcipts[i].src = newSrc; // Your source here
    break;
  }
}

If the entire url might change, you will want to look into a different solution (ids, placement on page, etc).

like image 61
Matt Bryant Avatar answered Sep 13 '26 04:09

Matt Bryant


If this isn't server side javascript, you're wasting your time. Removing a script element once it's in the page is pointless. Once a script is loaded, it's loaded, you can't "unload" it. Nothing you can do short of navigating to a new URL will change that.

Replacing the src of a script element is similarly pointless, you might as well just load a new element. Replacing the src doesn't unload the script content (see above), it just removes the element.

If you want to load a different script in the page, you must do that at the server.

like image 31
RobG Avatar answered Sep 13 '26 02:09

RobG