Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My HTML block as follows,

<html>
<title>Example</title>
<head>
</head>
<body>
        <h2>Profile Photo</h2>
    <div id="photo-container">Photo will load here</div>
    <script type='text/javascript' src='http://example.com/js/coverphoto.js?name=johndoe'></script>
</body>
</html>

and I have saved this file as test.html. In JavaScript source the name will be dynamic. I want to collect the name in coverphoto.js. Tried in coverphoto.js as,

window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')

but it is getting the html file name (test.html) only. How can I retrieve the name key from http://example.com/js/coverphoto.js?name=johndoe in coverphoto.js?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

To get the URL of the current JavaScript file you can use the fact that it will be the last <script> element currently on the page.

var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
var scriptURL = script.src;

Please note that this code will only work if it executes directly within the JS file, i.e. not inside a document-ready callback or anything else that's called asynchronously. Then you can use any "get querystring parameter" JS (but make sure to replace any location.search references in there) to extract the argument.

I'd suggest you to put the value in a data-name argument though - that way you can simply use e.g. script.getAttribute('data-name') to get the value.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.