0

Using this post, I'm trying to load document via ajax and find contents of specific document node(s) so that I can display them without re-navigating browser.

However, my document always seems to be an empty document.

Ajax callback:

function processRatingToken(data) {  //Data is just standart HTML document string
  var doc = document.implementation.createHTMLDocument();
  doc.open();
  //Replace scripts
  data = data.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
  //Write HTML to the new document
  doc.write(data);
  doc.close();

  console.log(doc.body);  //Empty
}

So what's wrong?

Note: I'm using this strategy, because I'm building a Greasemonkey Userscript. If you are developing an Ajax application, this strategy is NOT recomended. Use JSON instead.

Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • It seems you cannot use `document.write` method due to cross-original policy in your greasemonkey userscript. – tenbits Nov 02 '13 at 15:41
  • No errors were thrown. And how come `.getElementById` works properly...? – Tomáš Zato Nov 02 '13 at 16:33
  • 1
    The CORS limitiation seems to be for `open/write` methods only. But not sure why. [see mdn](https://developer.mozilla.org/en-US/docs/Web/API/document.open) – tenbits Nov 02 '13 at 17:03
  • So the question is how to avoid changing document origin by document write... – Tomáš Zato Nov 02 '13 at 19:26
  • You found ya a way out with `innerHTML`. And I would say `innerHTML` is more prefered, than `document.write`! Or are there some other circumstances, that you need to use `write`? – tenbits Nov 02 '13 at 19:34
  • Yep, there are circumstances when I may want the scripts to be executed (including more document writes). Maybe there could be some `iframe` workaround. For this specific case `.innerHTML` is just fine. – Tomáš Zato Nov 02 '13 at 22:57

1 Answers1

0

There is a workaround with .innerHTML property:

doc.childNodes[1].innerHTML = data;

Where .childNodes[1] is the <html> element.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778