How to print javascript variables and show them in console? - javascript

I'm trying to implement google ads conversion on my website and as per the google team, I added the tags they gave yet the conversion is not showing up properly.
After getting in touch with one of the team members, he told me to correct the code:
So far My code:
I m passing an email value through the URL to the 'Thank-you' page.
I m echoing the value inside a hidden input tag and calling it back using ID in javascript
I can get the value from the input and print it in the console.
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": email_for_ads
};
console.log(email_for_ads);
</script>
I can see the email id in the console, and I'm sure the value is being fetched.
But he said it should be like below upon inspect :
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": "some#email.com"
};
console.log("some#email.com");
</script>
I even tried the below code too
var baseUrl = (window.location).href; // You can also use document.URL
var email_for_ads = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
//var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": email_for_ads
};
console.log(email_for_ads);
yet the same output. I can see the value in the console but on inspect. But he insists that it is that way and could be able to see the email value directly in inspecting itself.
Can someone understand, whether this is possible, if so, how can i do it.

It's possible, but very very weird, and I'd highly recommend against it - it doesn't provide any benefits except, I guess, when debugging, but when debugging it'd be easier to just retrieve the input value.
If you wanted the input value to be printed directly in the <script> tag, you'd have to create the script tag dynamically, either with document.createElement('script') or document.write.
For that to be possible, you'd need another script tag to create the dynamic script tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
// remove this script tag
document.currentScript.remove();
// append new script tag, with the input value directly in the source code
const email_for_ads_first = $("#email_for_ads").val();
document.write(`
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": "${email_for_ads_first}"
};
console.log("${email_for_ads_first}");
// log this script tag contents, so you can see what's in it:
console.log(document.currentScript.textContent);
<\/script>
`);
</script>
There's no good reason do this. Please don't.

You may need a server-side rendering technology to generate your email value into your HTML and scripts.
You can consider starting a service in nodejs, get the email value in the request,and in the responseļ¼Œreturn the email with your html and scripts.

Related

How to pass arguments to external Javascript files? [duplicate]

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>

Append javascript to HTML fields using through javascript

I'm currently trying to create a form dynamically through javascript after looking at this post. Everything is going smoothly until when I attempt to insert javascript to the input form's value field. I am thinking of something like this
<input type = 'hidden' name = 'q' value = '<script>...some_script...</script>'
Here is my attempt at achieving what I want above
my_form = document.createElement('form');
my_form.name = 'form_A';
....
my_tb = document.createElement('input');
my_tb.type = 'hidden';
my_tb.name = 'q';
my_tb.id = 'query';
my_tb.value = '<script>alert(document.cookie)</script>';
my_form.appendChild(my_tb);
document.body.appendChild(my_form);
document.form_A.submit();
The problem is that something is wrong (or maybe even illegal) with the line my_tb.value = '<script>alert(document.cookie)</script>'; When I run the file in my browser, it prints out all the javascript in the browser after that line, and in the developer console it says Uncaught SyntaxError: Unexpected token ILLEGAL
Is there a way to achieve what I want above while still using javascript to create form_A ? The main reason is what I was hoping I can store the value of document.cookie in a variable in javascript and use it later.
Any help would be appreciated.
Here is an example.
Create index.html file and paste the below.
<html>
<head>
<title></title>
</head>
<body>
<script>
// your site sets a cookie
document.cookie="username=John Doe";
my_form = document.createElement('form');
my_tb = document.createElement('input');
my_tb.value = document.cookie;
my_form.appendChild(my_tb);
document.body.appendChild(my_form);
alert(my_tb.value);
</script>
</body>
</html>
Run a server python -m SimpleHTTPServer
Open http://localhost:8000/

Get script content [duplicate]

If I have a script tag like this:
<script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case.
tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <script> tag, or it would break same-origin-policy.
long version:
Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a <script> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <script src=[url]></script> would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS, to get the content.
With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.
function printScriptTextContent(script)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",script.src)
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("the script text content is",xhr.responseText);
}
};
xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);
and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat
Do you want to get the contents of the file http://www.example.com/script.js? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
Update: HTML Imports are now deprecated (alternatives).
---
I know it's a little late but some browsers support the tag LINK rel="import" property.
http://www.html5rocks.com/en/tutorials/webcomponents/imports/
<link rel="import" href="/path/to/imports/stuff.html">
For the rest, ajax is still the preferred way.
I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.
yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use jQuery.load(...), the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <br> into your (scriptNode).innerText, and things like that. Then, if you use jQuery.getScript(...), the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)
I found it best to use jQuery.ajax with dataType: "text"
I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.
Here is code, tested and working:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script id="scriptData">
var scriptData = [
{ name: "foo" , url: "path/to/foo" },
{ name: "bar" , url: "path/to/bar" }
];
</script>
<script id="scriptLoader">
var LOADER = {
loadedCount: 0,
toBeLoadedCount: 0,
load_jQuery: function (){
var jqNode = document.createElement("script");
jqNode.setAttribute("src", "/path/to/jquery");
jqNode.setAttribute("onload", "LOADER.loadScripts();");
jqNode.setAttribute("id", "jquery");
document.head.appendChild(jqNode);
},
loadScripts: function (){
var scriptDataLookup = this.scriptDataLookup = {};
var scriptNodes = this.scriptNodes = {};
var scriptNodesArr = this.scriptNodesArr = [];
for (var j=0; j<scriptData.length; j++){
var theEntry = scriptData[j];
scriptDataLookup[theEntry.name] = theEntry;
}
//console.log(JSON.stringify(scriptDataLookup, null, 4));
for (var i=0; i<scriptData.length; i++){
var entry = scriptData[i];
var name = entry.name;
var theURL = entry.url;
this.toBeLoadedCount++;
var node = document.createElement("script");
node.setAttribute("id", name);
scriptNodes[name] = node;
scriptNodesArr.push(node);
jQuery.ajax({
method : "GET",
url : theURL,
dataType : "text"
}).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node));
}
},
makeFailHandler: function(name, node){
var THIS = this;
return function(xhr, errorName, errorMessage){
console.log(name, "FAIL");
console.log(xhr);
console.log(errorName);
console.log(errorMessage);
debugger;
}
},
makeHandler: function(name, node){
var THIS = this;
return function (fileContents, status, xhr){
THIS.loadedCount++;
//console.log("loaded", name, "content length", fileContents.length, "status", status);
//console.log("loaded:", THIS.loadedCount, "/", THIS.toBeLoadedCount);
THIS.scriptDataLookup[name].fileContents = fileContents;
if (THIS.loadedCount >= THIS.toBeLoadedCount){
THIS.allScriptsLoaded();
}
}
},
allScriptsLoaded: function(){
for (var i=0; i<this.scriptNodesArr.length; i++){
var scriptNode = this.scriptNodesArr[i];
var name = scriptNode.id;
var data = this.scriptDataLookup[name];
var fileContents = data.fileContents;
var textNode = document.createTextNode(fileContents);
scriptNode.appendChild(textNode);
document.head.appendChild(scriptNode); // execution is here
//console.log(scriptNode);
}
// call code to make the frames here
}
};
</script>
</head>
<frameset rows="200pixels,*" onload="LOADER.load_jQuery();">
<frame src="about:blank"></frame>
<frame src="about:blank"></frame>
</frameset>
</html>
related question
.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.
In a comment to my previous answer:
I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)
In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.
if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.
This might be of interest: http://ejohn.org/blog/degrading-script-tags/
I had a same issue, so i solve it this way:
The js file contains something like
window.someVarForReturn = `content for return`
On html
<script src="file.js"></script>
<script>console.log(someVarForReturn)</script>
In my case the content was html template. So i did something like this:
On js file
window.someVarForReturn = `<did>My template</div>`
On html
<script src="file.js"></script>
<script>
new DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]
</script>
You cannot directly get what browser loaded as the content of your specific script tag (security hazard);
But
you can request the same resource (src) again ( which will succeed immediately due to cache ) and read it's text:
const scriptSrc = document.querySelector('script#yours').src;
// re-request the same location
const scriptContent = await fetch(scriptSrc).then((res) => res.text());
If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.
It will allow you to get each of the script attributes.
If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.
It's funny but we can't, we have to fetch them again over the internet.
Likely the browser will read his cache, but a ping is still sent to verify the content-length.
[...document.scripts].forEach((script) => {
fetch(script.src)
.then((response) => response.text() )
.then((source) => console.log(source) )
})
Using 2008-style DOM-binding it would rather be:
document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");
You want to use the innerHTML property to get the contents of the script tag:
document.getElementById("myscript").innerHTML
But as #olle said in another answer you probably want to have a read of:
http://ejohn.org/blog/degrading-script-tags/
If a src attribute is provided, user agents are required to ignore the content of the element, if you need to access it from the external script, then you are probably doing something wrong.
Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.
I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.
So Sugendran should be correct (not sure why he was voted down without explanation).
var scriptContent = document.getElementById("myscript").innerHTML;
The innerHTML property of the script element should give you the scripts content as a string provided the script element is:
an inline script, or
that the script has loaded (if using the src attribute)
olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.
if you where to have the js between and you could access it through innerHTML.
Regarding the usefulness of this technique:
I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.
Not sure why you would need to do this?
Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

Use of "switch" in Chrome-app versus in regular webpages

I have a small web application in html/js which works perfectly if you open it in a regular browser. I wanted to adapt the code to be able to run it like a Chrome app (my first Chrome app, by the way), and I did all the necessary changes according to the documentation I read: I got rid of inline js, downloaded local copies of jquery, replaced the onclick with event listeners... Now everything works well inside the Chrome app. There is just one thing that doesn't: a switch selector that updates a variable according to what has been selected in a select list. This works well in the regular webpage, but if you run it inside the Chrome app, it's as if the app is ignoring the switch and never updating the values.
Is there any limitation or anything I should take into account in this case? Can it be possible that I need to structure it in a different way to fit the Chrome app requirements?
The code itself:
In the html file we have a text box, whose value will be modified according to what we select in the list. There is also a second text box disabled that will display the result:
<input type="text" class="ctext" placeholder="DJN code" id="code">
<input type="text" class="ctext" id="ft" disabled="true" >
<select id="combobox">
<option value="tiranastockexchange">TIRANA Tirana Stock Exchange</option>
and so on...
in the .js file we have a function which interacts with the select box in the following way:
function convert() {
var str = document.getElementById('code').value
var root = str.replace(/^.*\/|\.[^.]*$/g, '');
var djticker= "";
var prefix = "";
var ct = "";
var notes = "";
var web = "";
var ex = document.getElementById('combobox');
var selex = ex.options[ex.selectedIndex].value;
switch(selex) {
case "tiranastockexchange":
prefix = "aT";
break;
//and the rest of cases following the same structure...
}
After the switch, if I operate with strings and use the value of prefix, I am still getting value "" instead of "aT", as if the whole switch is ignored. The following is what comes after the switch, just before closing the function:
djticker = prefix+root;
var nfield = document.getElementById("notes");
nfield.value = notes;
var result = document.getElementById("ft");
result.value = djticker;
So if the value of code is ASDF.AS and in the select box you select the value with the value tiranastockexchange , the textbox with the id ft should display aTASDF
For that, I have an event listener attached to a button in the html file with the id convert:
document.addEventListener('DOMContentLoaded', function() {
var cf = document.getElementById('convert');
cf.addEventListener('click', function() {
convert();
});
});
In the other hand, if you run this very same code in a regular html file, it works perfectly.
What could make the difference?
Thanks!

How to get the currently loading script name and the url variable of the script?

I am loading a script using the script embed tag and I want to get the url variables and the loading script name inside the script. Is it possible? For Example,
<script src="test.js?id=12"></script>
Inside test.js is there any way to get the url variable id?
Any help would be appreciated.
Thanks,
Karthik
Aside from the answers in the linked post, FWIW with Firefox 4 only you can (with caveats); document.currentScript.src which will return the full url, including arguments.
Thanks for all your efforts I have made that working by assigning an id attribute in the script tag and accessed via jQuery,
<script src="test.js?id=12" id="myScript"></script>
var currentScript = $("#myScript").attr('src'); //This will give me my script src
Thanks,
Karthik
If you want to get a variable from the current URL you can use this:
function queryParser(url){
this.get=function(p){return this.q[p];}
this.q={};
this.map=function(url){
url=url || window.location.search.substring(1);
var url=url.split('&');
var part;
for(var i=0;i<url.length;i++){
part=url[i].split('=');
this.q[part[0]]=part[1];
}
}
this.map(url);
}
var query=new queryParser();
// assuming you have ?test=something
alert(query.get('test'));
I recommend you map the result, so you don't re-parse whenever you want to find a specific element.
I don't really know why you'd pass a query string in a script tag like that, unless you specifically want off-site includes with a simple robust system for various effects. Or are actually using PHP to handle that request.
If you want to "send" a variable to one of your scripts, you can always do:
<script type="text/javascript">
var myVar="I'm in global scope, all scripts can access me";
</script>
<script src="test.js?id=12"></script>
If you really need to get the URL of the currently included script, you can use the code supplied by my peers in the other answers, you can then use:
var query=new queryParser(scriptURL);
alert(query.get('id'));// would alert 12 in your case
Navigating through the link on your comments you can get the proper answer.
Anyway, to make things easier:
var allScripts=document.getElementsByTagName('script');
var indexLastScript= allScripts.length -1;
alert (allScripts[indexLastScript].src);
This will show up "test.js?id=12" as a regular String so its up to you to split it in order to get de param.
Hope it helps, I've tried it on the run over the Chrome Javascript Console. :D.

Categories

Resources