How to get query parameter from the script source? [duplicate] - javascript

I read the tutorial DIY widgets - How to embed your site on another site for XSS Widgets by Dr. Nic.
I'm looking for a way to pass parameters to the script tag. For example, to make the following work:
<script src="http://path/to/widget.js?param_a=1&param_b=3"></script>
Is there a way to do this?
Two interesting links:
How to embed Javascript widget that depends on jQuery into an unknown environment (Stackoverflow discussion)
An article on passing parameters to a script tag

I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.
<script src=".." one="1" two="2"></script>
Inside above script:
document.currentScript.getAttribute('one'); // 1
document.currentScript.getAttribute('two'); // 2
Much easier than jQuery or URL parsing.
You might need the polyfill for document.currentScript from #Yared Rodriguez's answer for IE:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();

It's better to Use feature in html5 5 data Attributes
<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>
Inside the script file http://path.to/widget.js you can get the paremeters in that way:
<script>
function getSyncScriptParams() {
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript;
return {
width : scriptName.getAttribute('data-width'),
height : scriptName.getAttribute('data-height')
};
}
</script>

Got it. Kind of a hack, but it works pretty nice:
var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];
I pass the params in the script tag as classes:
<script src="http://path.to/widget.js" class="2 5 4"></script>
This article helped a lot.

Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:
<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />
The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):
var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;
Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...

JQuery has a way to pass parameters from HTML to javascript:
Put this in the myhtml.html file:
<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>
In the same directory make a subscript.js file and put this in there:
//Use jquery to look up the tag with the id of 'myscript' above. Get
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");
//print filename out to screen.
document.write(filename);
Analyze Result:
Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.
jsfiddle proof that the above works:
http://jsfiddle.net/xqr77dLt/

Create an attribute that contains a list of the parameters, like so:
<script src="http://path/to/widget.js" data-params="1, 3"></script>
Then, in your JavaScript, get the parameters as an array:
var script = document.currentScript ||
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();
var params = (script.getAttribute('data-params') || '').split(/, */);
params[0]; // -> 1
params[1]; // -> 3

If you are using jquery you might want to consider their data method.
I have used something similar to what you are trying in your response but like this:
<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>
You could also create a function that lets you grab the GET params directly (this is what I frequently use):
function $_GET(q,s) {
s = s || window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
// Grab the GET param
var param_a = $_GET('param_a');

Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.
HTML:
<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
<button id='clickButton'>Click me</button>
</div>
JavaScript:
$(document).ready(function() {
var fetchData = $("#dataDiv").data('arg1') +
$("#dataDiv").data('arg2') ;
$('#clickButton').click(function() {
console.log(fetchData);
})
});
Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0
On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.
Source: https://api.jquery.com/data/

it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.
Basically I used the document.currentScript to get the element from where my code is running and I filter using the name of the variable I am looking for. I did it extending currentScript with a method called "get", so we will be able to fetch the value inside that script by using:
document.currentScript.get('get_variable_name');
In this way we can use standard URI to retrieve the variables without adding special attributes.
This is the final code
document.currentScript.get = function(variable) {
if(variable=(new RegExp('[?&]'+encodeURIComponent(variable)+'=([^&]*)')).exec(this.src))
return decodeURIComponent(variable[1]);
};
I was forgetting about IE :) It could not be that easier... Well I did not mention that document.currentScript is a HTML5 property. It has not been included for different versions of IE (I tested until IE11, and it was not there yet). For IE compatibility, I added this portion to the code:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
What we are doing here is to define some alternative code for IE, which returns the current script object, which is required in the solution to extract parameters from the src property. This is not the perfect solution for IE since there are some limitations; If the script is loaded asynchronously. Newer browsers should include ".currentScript" property.
I hope it helps.

This is the Solution for jQuery 3.4
<script src="./js/util.js" data-m="myParam"></script>
$(document).ready(function () {
var m = $('script[data-m][data-m!=null]').attr('data-m');
})

Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.

It's simpler if you pass arguments without names, just like function calls.
In HTML:
<script src="abc.js" data-args="a,b"></script>
Then, in JavaScript:
const args=document.currentScript.dataset.args.split(',');
Now args contains the array ['a','b']. This assumes synchronous script calling.

I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScript or the data attributes method would be most stylish.
This is the only of these methods not brought up here yet. Particularly, if for some reason you have great amounts of data, then the best option might be:
localStorage
/* On the original page, you add an inline JS Script.
* If you only have one datum you don't need JSON:
* localStorage.setItem('datum', 'Information here.');
* But for many parameters, JSON makes things easier: */
var data = {'data1': 'I got a lot of data.',
'data2': 'More of my data.',
'data3': 'Even more data.'};
localStorage.setItem('data', JSON.stringify(data));
/* External target JS Script, where your data is needed: */
var data = JSON.parse(localStorage.getItem('data'));
console.log(data['data1']);
localStorage has full modern browser support, and surprisingly good support of older browsers too, back to IE 8, Firefox 3,5 and Safari 4 [eleven years back] among others.
If you don't have a lot of data, but still want extensive browser support, maybe the best option is:
Meta tags [by Robidu]
/* HTML: */
<meta name="yourData" content="Your data is here" />
/* JS: */
var data1 = document.getElementsByName('yourData')[0].content;
The flaw of this, is that the correct place to put meta tags [up until HTML 4] is in the head tag, and you might not want this data up there. To avoid that, or putting meta tags in body, you could use a:
Hidden paragraph
/* HTML: */
<p hidden id="yourData">Your data is here</p>
/* JS: */
var yourData = document.getElementById('yourData').innerHTML;
For even more browser support, you could use a CSS class instead of the hidden attribute:
/* CSS: */
.hidden {
display: none;
}
/* HTML: */
<p class="hidden" id="yourData">Your data is here</p>

Related

Get the referral <script> object in JS in the source script

Assuming we have a script tag in html:
<script mycustom-attribute="sample-value" src="http://example.com/myscript.js"></script>
Now, is there anyway, where we can get the caller script object in "myscript.js" so that we can read mycustom-attribute. Of course we can use some id/class, but what if we want to refer it without its name/id/class. The idea is to use to embed widget without having a problem of conflicting id/name/class.
You can select the script which has the custom attribute:
var script = document.querySelector('script[mycustom-attribute]');
if (script) {
var value = script.getAttribute('mycustom-attribute');
console.log(value);
}
Since you have a custom attribute to work with, see Neil's answer.
If there could be multiple scripts with the custom attribute, or for those who don't have a custom attribute to work with:
Assuming your script tag is as shown, without async or defer, then in top-level code in that script, you know reliably that it's the last script in the DOM, so:
var scripts = document.getElementsByTagName("script");
var value = scripts[scripts.length - 1].getAttribute("mycustom-attribute");
If there may be an async or defer, you need to look by src, perhaps using the "ends with" attribute selector ($=):
var script = document.querySelector("script[src$='myscript.js']");
var value = script.getAttribute("mycustom-attribute");
(There's also document.currentScript, but it's "...fallen out of favor in the implementer and standards community...".)
Side note: When using custom attributes, use the data- prefix.

Odd URL Callback performance. How do It know?

I'm studying very closely a YQL query example. There is a html script call to an API url address with callback function identified.
If I include the callback as a separate <script></script> things work fine. It totally fails if the code is contained in a single <script></script> tag.
This works:
<script>
function top_stories(o) {
var items = o.query.results.item;
var output = '';
var no_items = items.length;
for (var i = 0; i < no_items; i++) {
var title = items[i].title;
var link = items[i].link;
var desc = items[i].description;
output += "<h3><a href='" + link + "'>" + title + "</a></h3>" + desc + "<hr/>";
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
</script>
<script src='https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&callback=top_stories'></script>
While this next bit fails to function at all.
<script>
function top_stories(o) {
var items = o.query.results.item;
(... same as above)
document.getElementById('results').innerHTML = output;
}
src='https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20rss%20where%20url%3D%22http%3A%2F%2Frss.news.yahoo.com%2Frss%2Ftopstories%22&format=json&callback=top_stories';
</script>
Non functional jsfiddle: https://jsfiddle.net/ogcoaaff/
Swap a few comments and success: https://jsfiddle.net/ogcoaaff/1/
I don't believe this is a timing / loading sequence issue. No way. I was pretty careful to push the scripts into the jsfiddle HTML box and not the script box. I did not want to use jQuery and have that cloud the discussion.
Can someone explain what's going on here? What am I missing? (Note: I was hoping to run a quick call to a YQL api from totally within a javascript file in another application where I don't have access to <script> calls. (and where I can't use $.JSON and prefer not to use XMLHttpRequest().)
I'd just really would like to understand what is happening here. Anybody know the details (or better yet, a tech reference explaining this behavior?)
Many thanks.
The <script> element has two relatively distinct uses:
Load external JavaScript:
<script src="URL"></script>
Embed a piece of JavaScript:
<script>
// code here
</script>
Your working example uses both of these uses: one to embed a script into the page (containing the top_stories function), and one to retrieve an external script from Yahoo.
Your non-working example is, simply put, just invalid. The src part is an attribute of the <script> element, so it can only be used with the <script ....> block.
Don't be tempted to think that mixing them properly will work, though:
<script src="URL">
// code here
</script>
This won't work, or at least won't work reliably (I believe that this isn't even allowed according to the HTML standard).
I was hoping to run a quick call to a YQL api from totally within a javascript file in another application where I don't have access to <script> calls.
You can programmatically create <script> elements. See this question or this question to get an idea on how that would work.

Javascript: Detect/Prevent External Scripts

Is it possible to detect external scripts that might be loaded into a page by browser add-ons, a proxy, xss, etc?
Say I have this web page:
<html>
<head>
<title>Hello world!</title>
<script src="http://mydomain.com/script.js"></script>
</head>
<body>
Hello world!
</body>
</html>
Would it be possible to include some script in my script.js file that would detect when other script elements on the page do not originate from http://mydomain.com?
I want something that could detect other scripts somehow included in the source (i.e. they are present when the onload event fires) and scripts added any time after page load.
If I can detect those scripts, can I also stop them somehow?
This would be useful in debugging javascript/ui issues reported by users if I knew there was other stuff going on.
I use jQuery, so a jQuery answer will work for me. I just didn't want to limit answers to jQuery only.
EDIT
My solution is below. However, there are two (potential) problems with it:
It depends on jQuery.
It will not detect foreign resources loaded via CSS #import rules (or any rule with a url() value).
If someone would like to submit an answer that solves one or both of those issues, I will upvote it.
If you solve both, I will accept your answer.
You could check all script elements on domready like this:
$(function () {
$('script').each(function () {
check script source here
})
})
but, if someone could inject script tags in your side, he can also delete your code before you can start the check, also it will be hard to delete objects and functions the script could create before your recognize it.
So I dont think its a good solution to start investing time in this field. Its much more important to be clear that you cant trust the client anyway.
As you wanna figure out it anyway there are a bunch of DOM events to check if the DOM tree has changed.
I wasn't satisfied with the answers I received (though I appreciate Andreas Köberle's advice), so I decided to tackle this myself.
I wrote a function that could be run on demand and identify any html elements with foreign sources. This way, I can run this whenever reporting a javascript error to get more information about the environment.
Code
Depends on jQuery (sorry, element selection was just so much easier) and parseUri() (copied at the bottom of this answer)
/**
* Identifies elements with `src` or `href` attributes with a URI pointing to
* a hostname other than the given hostname. Defaults to the current hostname.
* Excludes <a> links.
*
* #param string myHostname The hostname of allowed resources.
* #return array An array of `ELEMENT: src` strings for external resources.
*/
function getExternalSources(myHostname)
{
var s, r = new Array();
if(typeof myHostname == 'undefined')
{
myHostname = location.hostname;
}
$('[src], [href]:not(a)').each(function(){
s = (typeof this.src == 'undefined' ? this.href : this.src);
if(parseUri(s).hostname.search(myHostname) == -1)
{
r.push(this.tagName.toUpperCase() + ': ' + s);
}
});
return r;
}
Usage
var s = getExternalSources('mydomain.com');
for(var i = 0; i < s.length; i++)
{
console.log(s[i]);
}
// Can also do the following, defaults to hostname of the window:
var s = getExternalSources();
The search is inclusive of subdomains, so elements with sources of www.mydomain.com or img.mydomain.com would be allowed in the above example.
Note that this will not pick up on foreign sources in CSS #import rules (or any CSS rule with a url() for that matter). If anyone would like to contribute code that can do that, I will upvote and accept your answer.
Below is the code for parseUri(), which I obtained from https://gist.github.com/1847816 (and slightly modified).
(function(w, d){
var a,
k = 'protocol hostname host pathname port search hash href'.split(' ');
w.parseUri = function(url){
a || (a = d.createElement('a'));
a.href = url;
for (var r = {}, i = 0; i<8; i++)
{
r[k[i]] = a[k[i]];
}
r.toString = function(){return a.href;};
r.requestUri = r.pathname + r.search;
return r;
};
})(window, document);
You could listen for changes in DOM and see if a new script tag is being inserted. But may I ask, what is the reason for such a need? I doubt you will be able to detect all possible cases where some arbitrary JS is executed against your page's DOM (e.g. a bookmarklet, or greasemonkey script).
I think the same origin policy may cover this:
http://en.wikipedia.org/wiki/Same_origin_policy

How do you get the contextPath from JavaScript, the right way?

Using a Java-based back-end (i.e., servlets and JSP), if I need the contextPath from JavaScript, what is the recommended pattern for doing that, any why? I can think of a few possibilities. Am I missing any?
1. Burn a SCRIPT tag into the page that sets it in some JavaScript variable
<script>var ctx = "<%=request.getContextPath()%>"</script>
This is accurate, but requires script execution when loading the page.
2. Set the contextPath in some hidden DOM element
<span id="ctx" style="display:none;"><%=request.getContextPath()%></span>
This is accurate, and doesn't require any script execution when loading the page. But you do need a DOM query when need to access the contextPath. The result of the DOM query can be cached if you care that much about performance.
3. Try to figure it out within JavaScript by examining document.URL or the BASE tag
function() {
var base = document.getElementsByTagName('base')[0];
if (base && base.href && (base.href.length > 0)) {
base = base.href;
} else {
base = document.URL;
}
return base.substr(0,
base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1));
};
This doesn't require any script execution when loading the page, and you can also cache the result if necessary. But this only works if you know your context path is a single directory -- as opposed to the root directory (/) or the multiple directories down (/mypath/iscomplicated/).
Which way I'm leaning
I'm favoring the hidden DOM element, because it doesn't require JavaScript code execution at the load of the page. Only when I need the contextPath, will I need to execute anything (in this case, run a DOM query).
Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:
<script>var ctx = "${pageContext.request.contextPath}"</script>
Got it :D
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());
Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.
I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.
You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.
At this point I agree with #BalusC to use EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
or depending on the version of JSP fallback to JSTL:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
Reviewer the solution by this
Checking the solution of this page, make the following solution I hope it works:
Example:
Javascript:
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";
I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:
<html>
<head>
<link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
main.js
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});
If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string
A Spring Boot with Thymeleaf solution could look like:
Lets say my context-path is /app/
In Thymeleaf you can get it via:
<script th:inline="javascript">
/*<![CDATA[*/
let contextPath = /*[[#{/}]]*/
/*]]>*/
</script>

How to pass parameters to a Script tag?

I read the tutorial DIY widgets - How to embed your site on another site for XSS Widgets by Dr. Nic.
I'm looking for a way to pass parameters to the script tag. For example, to make the following work:
<script src="http://path/to/widget.js?param_a=1&param_b=3"></script>
Is there a way to do this?
Two interesting links:
How to embed Javascript widget that depends on jQuery into an unknown environment (Stackoverflow discussion)
An article on passing parameters to a script tag
I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.
<script src=".." one="1" two="2"></script>
Inside above script:
document.currentScript.getAttribute('one'); // 1
document.currentScript.getAttribute('two'); // 2
Much easier than jQuery or URL parsing.
You might need the polyfill for document.currentScript from #Yared Rodriguez's answer for IE:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
It's better to Use feature in html5 5 data Attributes
<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>
Inside the script file http://path.to/widget.js you can get the paremeters in that way:
<script>
function getSyncScriptParams() {
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript;
return {
width : scriptName.getAttribute('data-width'),
height : scriptName.getAttribute('data-height')
};
}
</script>
Got it. Kind of a hack, but it works pretty nice:
var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];
I pass the params in the script tag as classes:
<script src="http://path.to/widget.js" class="2 5 4"></script>
This article helped a lot.
Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:
<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />
The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):
var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;
Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...
JQuery has a way to pass parameters from HTML to javascript:
Put this in the myhtml.html file:
<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>
In the same directory make a subscript.js file and put this in there:
//Use jquery to look up the tag with the id of 'myscript' above. Get
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");
//print filename out to screen.
document.write(filename);
Analyze Result:
Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.
jsfiddle proof that the above works:
http://jsfiddle.net/xqr77dLt/
Create an attribute that contains a list of the parameters, like so:
<script src="http://path/to/widget.js" data-params="1, 3"></script>
Then, in your JavaScript, get the parameters as an array:
var script = document.currentScript ||
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();
var params = (script.getAttribute('data-params') || '').split(/, */);
params[0]; // -> 1
params[1]; // -> 3
If you are using jquery you might want to consider their data method.
I have used something similar to what you are trying in your response but like this:
<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>
You could also create a function that lets you grab the GET params directly (this is what I frequently use):
function $_GET(q,s) {
s = s || window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
// Grab the GET param
var param_a = $_GET('param_a');
Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.
HTML:
<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
<button id='clickButton'>Click me</button>
</div>
JavaScript:
$(document).ready(function() {
var fetchData = $("#dataDiv").data('arg1') +
$("#dataDiv").data('arg2') ;
$('#clickButton').click(function() {
console.log(fetchData);
})
});
Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0
On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.
Source: https://api.jquery.com/data/
it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.
Basically I used the document.currentScript to get the element from where my code is running and I filter using the name of the variable I am looking for. I did it extending currentScript with a method called "get", so we will be able to fetch the value inside that script by using:
document.currentScript.get('get_variable_name');
In this way we can use standard URI to retrieve the variables without adding special attributes.
This is the final code
document.currentScript.get = function(variable) {
if(variable=(new RegExp('[?&]'+encodeURIComponent(variable)+'=([^&]*)')).exec(this.src))
return decodeURIComponent(variable[1]);
};
I was forgetting about IE :) It could not be that easier... Well I did not mention that document.currentScript is a HTML5 property. It has not been included for different versions of IE (I tested until IE11, and it was not there yet). For IE compatibility, I added this portion to the code:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
What we are doing here is to define some alternative code for IE, which returns the current script object, which is required in the solution to extract parameters from the src property. This is not the perfect solution for IE since there are some limitations; If the script is loaded asynchronously. Newer browsers should include ".currentScript" property.
I hope it helps.
This is the Solution for jQuery 3.4
<script src="./js/util.js" data-m="myParam"></script>
$(document).ready(function () {
var m = $('script[data-m][data-m!=null]').attr('data-m');
})
Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.
It's simpler if you pass arguments without names, just like function calls.
In HTML:
<script src="abc.js" data-args="a,b"></script>
Then, in JavaScript:
const args=document.currentScript.dataset.args.split(',');
Now args contains the array ['a','b']. This assumes synchronous script calling.
I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScript or the data attributes method would be most stylish.
This is the only of these methods not brought up here yet. Particularly, if for some reason you have great amounts of data, then the best option might be:
localStorage
/* On the original page, you add an inline JS Script.
* If you only have one datum you don't need JSON:
* localStorage.setItem('datum', 'Information here.');
* But for many parameters, JSON makes things easier: */
var data = {'data1': 'I got a lot of data.',
'data2': 'More of my data.',
'data3': 'Even more data.'};
localStorage.setItem('data', JSON.stringify(data));
/* External target JS Script, where your data is needed: */
var data = JSON.parse(localStorage.getItem('data'));
console.log(data['data1']);
localStorage has full modern browser support, and surprisingly good support of older browsers too, back to IE 8, Firefox 3,5 and Safari 4 [eleven years back] among others.
If you don't have a lot of data, but still want extensive browser support, maybe the best option is:
Meta tags [by Robidu]
/* HTML: */
<meta name="yourData" content="Your data is here" />
/* JS: */
var data1 = document.getElementsByName('yourData')[0].content;
The flaw of this, is that the correct place to put meta tags [up until HTML 4] is in the head tag, and you might not want this data up there. To avoid that, or putting meta tags in body, you could use a:
Hidden paragraph
/* HTML: */
<p hidden id="yourData">Your data is here</p>
/* JS: */
var yourData = document.getElementById('yourData').innerHTML;
For even more browser support, you could use a CSS class instead of the hidden attribute:
/* CSS: */
.hidden {
display: none;
}
/* HTML: */
<p class="hidden" id="yourData">Your data is here</p>

Categories