Reputation: 1659
I have a JavaScript file that embeds a widget on a website. I want to be able to call this widget using a URL of the form:
http://domain.com/widget.js?variable=test
Within the JS script I want to be able to read in the value of the URL parameter 'variable' which is this case is 'test' and use it in the HTML code the JS outputs. I tried using window.location but that is returning the URL of the main webpage and not the URL that is being called to load the script.
Any ideas what the JS code looks like to read in a passed parameter? Thanks in advance!
Upvotes: 2
Views: 5321
Reputation: 90062
Iterate through all <script>
elements using getElementsByTagName
. Find the one which identifies your script (e.g. by looking for domain.com/widget.js
) by examining the src
attribute. Extract the query string from the src
attribute.
Example:
function getScriptQuery(identifier) {
var scripts = document.getElementsByTagName('script'),
i, curScript;
for (i = 0; i < scripts.length; ++i) {
curScript = scripts[i];
if (curScript.src.match(identifier)) {
return (curScript.src.match(/\?.*/) || [undefined])[0];
}
}
}
alert(getScriptQuery('widget.js'));
There are two common alternatives to solving your original problem of passing data to the script.
You can reference a known global variable in your script and have the calling HTML define that variable:
<script type="text/javascript">var MyWidgetData={foo:'bar'};</script>
<script src="http://my.widgeteer.net/widget.js"></script>
// widget.js:
alert(MyWidgetData.foo);
You can also wrap your script as a named function and have calling HTML call that function:
<script src="http://my.widgeteer.net/widget.js"></script>
<script type="text/javascript">MyWidget({foo:'bar'});</script>
// widget.js:
function MyWidget(data) {
alert(data.foo);
}
Upvotes: 3