function injectDocumentWrite(targetWindow, doc) {
  var stackContainer = new Error();
  function processMarkup(markup) {
    if (markup.indexOf('<script ') == -1) {
      // Probably not a script tag. Ignore.
      return false;
    }

    // Try really hard to get base URLs.
    var baseUrl = arguments.callee.caller.caller ?
        arguments.callee.caller.caller['__src'] : null;
    if (!baseUrl) {
      var originalPrepare = Error.prepareStackTrace;
      Error.prepareStackTrace = function(e, callSites) {
        return callSites;
      };
      Error.captureStackTrace(stackContainer);
      var stack = stackContainer.stack;
      Error.prepareStackTrace = originalPrepare;
      baseUrl = stack[2].getFileName();
    }

    // We hackily do this by creating the DOM inside of a non-document-rooted
    // div and query all scripts. This lets us find multiple scripts/etc and
    // not have to worry about parsing HTML ourselves.
    var div = doc.createElement('div');
    div.innerHTML = markup;
    var scripts = div.querySelectorAll('script');
    if (!scripts || !scripts.length) {
      return false;
    }

    log('document.write* of scripts', scripts);

    // Process each script.
    // Since document.write* is synchronous, we must fetch and process inline.
    for (var n = 0; n < scripts.length; n++) {
      var script = scripts[n];
      var processedScript = processScript(script, true, baseUrl);
      // Eval in window context - with our sourceURL tag this lets the code
      // show in the dev tools correctly.
      eval.call(targetWindow, processedScript.text);
    }

    // TODO(benvanik): ensure we aren't eating other stuff that needs to go
    // into the DOM.
    return true;
  };

  var originalDocWrite = doc.write;
  doc.write = function write(markup) {
    if (processMarkup(markup)) {
      return;
    } else {
      return originalDocWrite.apply(this, arguments);
    }
  };
  doc.write['raw'] = originalDocWrite;

  var originalDocWriteLn = doc.writeln;
  doc.writeln = function writeln(line) {
    if (processMarkup(line)) {
      return;
    } else {
      return originalDocWriteLn.apply(this, arguments);
    }
  };
  doc.writeln['raw'] = originalDocWriteLn;
}
Instruments document.write* to look for script additions.
@param {!Document} doc Target document object.
@param {!Window} targetWindow Window.