How to determine calling script element?

59 Views Asked by At

My task at hand is creating a surrogate document.write() to make this functionality available under XHTML. Normally this function isn't available to avoid XHTML getting busted by nonsensical data written to the document, but under certain circumstances it could be viable to have a JavaScript that emulates this function, that is, take a string and parse it to create a DOM tree that can be inserted into the existing document. However, to find the spot where to insert this newly created tree I would have to find the location of the invoking script node in the document.

Attaching the function to the document node isn't a problem, because under XHTML it is extensible, and parsing the input string isn't that much of a problem, either. If errors are encountered, they are logged to the console, and an exception is thrown.

Considering a stripped-down version of document.write that is loaded from an external file:

document.write = function (p_arg)
  {
// X

// Do something with p_arg here
  };

Since this function is supposed to be called from anywhere within the document body, what would I have to insert at spot X to figure out where the call to this function came from (i. e. the script node that invoked the call)?

The following criteria need to be taken into account:

  • XHTML is being used so no document.write is available.
  • innerHTML is not an option, either, as it could also bust XHTML consistency.
  • The scriptlets' parent node could have an arbitrary ID (including none at all).
  • The script nodes aren't supposed to have an ID (the original document.write doesn't have to rely on that, either).
  • Auxiliary elements shouldn't be used to find out where the JavaScript is located.
  • jQuery and other libraries are not an option.

I want to come as close to the original document.write as possible, except where restrictions inherent to XHTML apply, to allow using preexisting codethat relies on that function.

Now, how do I find the spot where to insert the DOM tree generated by this function (that would be right before the node following the JavaScript or at the end if no successor is present)?

1

There are 1 best solutions below

2
On BEST ANSWER

Below is what I think your after.

It basically gets the currentScript that's running, find's it's parent and attaches the element.. I've not done the parsing part, so in this instance just pretending the <b>there</b> has been parsed and you have done all the createElement bits..

<script>
function docWrite(s) {
  //lets pretend we have parsed the s..
  //and it's <b>there</b>
  let b = document.createElement('b');
  b.textContent = 'there';
  let scr = document.currentScript;
  scr.parentNode.insertBefore(b, scr);  
}
</script>


<h1>Hello</h1>
<script>docWrite('<b>there</b>');</script>
<span>After</span>