1

We're writing some referral program code where our referrers will place a javascript file on their page whereever they want our logo to show up. Something like...

<script type="text/javascript" src="https://www.oursite.com/refer.js.asp?var=1"></script>

In the asp script it simply writes out a bit of code like...

document.write('<a href="oursite.com?referrer=somereferrer"><img src="logo.png"></a>');

While this works when running in a test page, I did find a situation where I get this error -

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

I get that error when I try to dynamically generate the script via a utility page and append it to a div on the page. Since the page has already loaded I can't use document.write in the script file. So, what I'm wondering is, is there a way that the script file can determine where it's located within the DOM to place the link and image at the right spot using something like...

var a = document.createElement('a');
var img = document.createElement('img');
img.src = img_url;
a.appendChild(img);
a.href = "http://www.oursite.com";
document.body.appendChild(a);

In this case I'm appending the a element directly to the body. What I need to be able to do is append it to whatever element contains the script file. Is that possible? If so, how? Thanks.

geoff swartz
  • 5,437
  • 11
  • 51
  • 75
  • 1
    Check out [this](http://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) and [this](http://stackoverflow.com/questions/4793604/how-to-do-insert-after-in-javascript-without-using-a-library) – musefan Jan 19 '17 at 14:36

2 Answers2

1

You can add id to your script element and use that id inside your script:

<script id="a1" type="text/javascript">
window.addEventListener('DOMContentLoaded', function() {
  var img = document.createElement('img');
  img.src = 'https://dummyimage.com/600x400/000/fff';
  document.getElementById('a1').nextSibling.parentNode.insertBefore(img, document.getElementById('a1').nextSibling);
});
</script>
Dekel
  • 60,707
  • 10
  • 101
  • 129
1

You could first try to find all script tags on the document, find yours via src match and then append to its parent.

Example:

var scriptTags = document.getElementsByTagName('script');
for(var i=0; i<scriptTags.length; i++) {
  if(scriptTags[i].src === "your script's href") {
    var parent = scriptTags[i].parentNode;
    //append your image/link to parent via parent.insertBefore(YOURNODE, scriptTags[i])
    break;
  }
}

You could also use regex to match for your src url if it isn't static

Michael Ritter
  • 580
  • 2
  • 9