Client-Side Dynamic Removal of [removed] Tags in <head>

后端 未结 5 2088
南笙
南笙 2021-01-31 10:37

Is it possible to remove script tags in the of an HTML document client-side and prior to execution of those tags?

On the server-side I am able

5条回答
  •  悲&欢浪女
    2021-01-31 11:13

    Ok so I have yet to test any of this in Internet Explorer (I doubt it'll work), and don't berate me for the horribleness of the hacks... I know ;) but it does seem to work in FireFox, Safari, Chrome and Opera on Mac OSX - the recent public releases of those useragents, at least. I'll see if I can improve it when I get access to a windows machine... although I don't hold much hope for IE.

    (function(xhr,d,de){
      d = document;
      try{
        de = ((de = d.getElementsByTagName('html')[0]) 
          ? de : ( d.documentElement ? d.documentElement : d.body ));
        /// this forces firefox to reasses it's dom
        d.write(' ');
        /// make an ajax request to get the source of this page as a string
        /// this could be improved, I've just chucked it in as an example
        if (window.XMLHttpRequest) {
          xhr = new window.XMLHttpRequest;
        }else{
          xhr = new ActiveXObject("MSXML2.XMLHTTP");
        }
        if ( xhr ) {
          /// open non-async so the browser has to wait
          xhr.open('GET', window.location, false);
          xhr.onreadystatechange = function (e,o,ns){
            /// when we've got the source of the page... then
            if ((o = e.target) && (o.readyState == 4) && (o.status == 200)) {
              /// remove the script tags
              window.ns = ns = String(o.responseText)
                  .replace(/]*>/gi,'<'+'!--')
                  .replace(/<\/script>/gi,'//--'+'>');
              /// fix for firefox - this causes a complete 
              /// rewrite of the main docelm
              if ( 'MozBoxSizing' in de.style ) {
                de.innerHTML = ns;
              }
              /// fix for webkit, this seems to work, whereas 
              /// normal document.write() doesn't. Probably 
              /// because the window.location resets the document.
              else {
                window.location = 'javascript:document.write(window.ns);';
              }
            }
          };
          xhr.send({});
        }
      }
      catch(ex){}
    })();
    

    Just to say I've tested this with nearly every type of script tag I can think of, placed where ever I could place them. And I haven't yet had one manage to break through. As I said, fun question... although I don't know how well the above would operate in a production environment :S ;)

    Basically this will have to be placed as a script tag right at the top of the head tag.

    A test example:

    http://pebbl.co.uk/stackoverflow/12748067.html

提交回复
热议问题