JavaScript Ninja – document.write Alternative

If you use document.write to write an entire new document,
Chrome might apply a security-policy, warning or even blocking every internal-script you have.

As an alternative, only use document.write to write the doctype,
and set the HTML-source using document.documentElement.innerHTML = ".......".

Here is a working code you, that should be loaded after the document has ready but before it rendered (a.k.a DOMContentLoaded or at_document_end if you are doing this in Chrome’s extension).

/* ╔════════════════════════════════════════════════════════════════════╗
   ║ at_document_end                                                    ║
   ╟────────────────────────────────────────────────────────────────────╢
   ║ File's content is injected immediately after the DOM is complete,  ║
   ║ - but before subresources like images and frames have loaded.      ║
   ║ - Like DOMContentLoaded                                            ║
   ╚════════════════════════════════════════════════════════════════════╝
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ */

(function (window, document, doctype, html, is_success_stream){ "use strict";
  try{html = document.documentElement.cloneNode(true).innerHTML;}catch(err){}
  if("undefined" === typeof html) return;

  try{window.stop();document.execCommand("Stop");document.clear();document.close();/*document.open();document.close();*/is_success_stream=true;}catch(err){}
  if(true !== is_success_stream)  return;

  /*
  //options #1  - rewrite new stream - good but will render extension's warning!!!
  html = doctype + html;  //fix
  html = html.replace(/http-equiv\s*=\s*[\'\"]refresh[\'\"]/gi, "done-metarefreshkiller");       
  document.open();document.write(html);document.close();  //(TODO: disable this?: chrome://flags/#disallow-doc-written-script-loads
  */
  
  //options #2  - avoid extension's warnings - minimal stream-write (just the doctype), other stuff: '.innerHTML'.
  document.open();document.write(doctype);document.close();
  html = html.replace(/http-equiv\s*=\s*[\'\"]refresh[\'\"]/gi, "done-metarefreshkiller");       
  document.documentElement.innerHTML = html;

}(
  self
, self.document
,
  (function(is_empty, EMPTY_STRING, SPACE, doctype){ "use strict";
    return "<!DOCTYPE##NAME####PUBLIC####PUBLICID####SYSTEM####SYSTEMID####INTERNALSUBSET##>"
            .replace("##NAME##",            true === is_empty(doctype.name)           ? EMPTY_STRING : SPACE + doctype.name                  )
            .replace("##PUBLIC##",          true === is_empty(doctype.publicId)       ? EMPTY_STRING : SPACE + "PUBLIC"                      )
            .replace("##PUBLICID##",        true === is_empty(doctype.publicId)       ? EMPTY_STRING : SPACE + '"' + doctype.publicId + '"'  )
            .replace("##SYSTEM##",          true === is_empty(doctype.systemId)
                                            || false === is_empty(doctype.publicId)   ? EMPTY_STRING : SPACE + "SYSTEM"                      )
            .replace("##SYSTEMID##",        true === is_empty(doctype.systemId)       ? EMPTY_STRING : SPACE + '"' + doctype.systemId + '"'  )
            .replace("##INTERNALSUBSET##",  true === is_empty(doctype.internalSubset) ? EMPTY_STRING : SPACE + '[' + doctype.systemId + ']'  )
          ;
  }(
   function is_empty(value){ return "undefined" === typeof value || null === value || "" === value; }
  ,""
  ," "
  ,self.document.doctype
  ,undefined
  ))
,
  undefined
,
  undefined
));

The code above is used to stop the loading and rendering of the current document, when executed at the DOMContentLoaded stage (or at_document_end if you’re doing this in a Chrome-extension),
then it gets the document’s current-doctype (or use a fallback if there is none), modifies the HTML slightly,
and put it back into the document, without actually triggering Chrome’s warning/block for Parser-blocking, cross-origin script, ......, is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity. See https://www.chromestatus.com/feature/5718547946799104 for more details..

get a fully working example,
github page: https://github.com/eladkarako/Chrome-Extension-Meta-Refresh-Killer.

Leave a Reply