0

I am embedding a external js file on some domains and I need to get the current location of the their URL to send to the server before the script is rendered and not after. I need to this dynamically so I cannot have the user specify the url themselves. For example I have a script:

<script type="text/javascript" src="file.js?url=NEED THIS"></script>

I would love to simply replace NEED THIS with window.location.href, however sadly this would not work. The main problem is that I need to get the url and parse it on the server side to generate the content file.js will deliver so I need this url passed to file.js at the beginning. How can I achieve this without using a iframe?

Alex
  • 209
  • 1
  • 2
  • 5

1 Answers1

0

Use a JavaScript to document.write an appropriate script tag!

<script>
    document.write('<scr'+'ipt src="file.js?url=' + encodeURIComponent(location.href) + '"></scr'+'ipt>');
</script>

Doing it this way, your users could still specify their own URL simply by putting the written script tag on the page instead of the above.

If you don't want this, you need to check for location.href in your JavaScript file.

Thai
  • 10,746
  • 2
  • 45
  • 57
  • Hey this looks like it can work, will do some testing. Can I ask why you separated ' – Alex May 09 '11 at 04:51
  • Usually a HTML parser stops parsing script tags whenever it has found the end tag ``. We need to separate them to prevent browser from doing this. Again you should check `location.href` in your JS instead anyway. – Thai May 09 '11 at 12:06