Fetching query string parameters passed in a javascript file

260 views Asked by At

I have used this tutorial to create a JS based widget. One thing I need to do is to pass query string parameters in JS file. I tried document.location.href but it gave the URL of page where widget was placed(which is quite obvious)

Code is given below:

<script src="http://example.com/widget.js?id=2" type="text/javascript"></script>
    <div id="widget"></div>

I need to fetch id=2 which I can pass further.

Thanks

1

There are 1 answers

3
tabz100 On BEST ANSWER

If you give your script an id then you can write:

<script src="http://example.com/widget.js?id=2" id="myscript" type="text/javascript"></script>
<div id="widget"></div>

<script>
var myScript = document.getElementById('myscript');
var src= myScript.getAttribute('src');
//Get the id from the src based on parameter using Regular Expression
</script>