Passing Javascript variables in URL - javascript

I am trying to pass a javascript variable to a php page via the URL. The code below triggers the php page but it doesn't get the variable. I have written the code using window.location.href and that works fine, the problem is doing it that way it loads the tracker.php page.
Below is my code.
<script type="text/javascript">
var siteId = "VT0013";
</script>
<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId="+ siteId ;>
</script>
PHP Page
$siteId = $_GET["siteId"];
Once I get the siteId I email the result as a test this works fine, except I am not getting the value of siteId. When using this same code with window.location.href it all works fine.

I'm guessing that since this is called tracker.php, you actually just need to hit this URL? If that's the case, consider using the Beacon API.
navigator.sendBeacon('https://example.com/tracker.php' {
siteId: 'VT0013'
});
This results in an HTTP POST request, but that's generally better for this anyway. You won't have to worry about caching. Also, the Beacon API will still work even if the request hasn't finished and the page is being unloaded.
If you actually do want to dynamically loads JavaScript instead, a current way to do that is to use import().
const siteId = 'VT0013';
await import (`https://example.com/tracker.php?siteId${encodeURIComponent(siteId)}`);
Finally, if you need to dynamically load this JavaScript and that script needs to run in the context of the rest of the page (i.e., not a module) then the best thing to do is inject a new script tag: https://stackoverflow.com/a/8578840/362536
No matter what you do, make sure you're escaping the data used in your URLs and in your HTML.

You can just do a quick XHR request if you want older browser support without polyfills:
var siteId = 'VT0013';
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', 'http://www.domainame.com/tracker.php?siteId=' + encodeURIComponent(siteId));
xhr.send();
This is just an alternate solution, #Brad's answer should be accepted.

You need to use document.write to write any HTML that contains JavaScript variables:
<script type="text/javascript">
var siteId = "VT0013";
document.write('<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId='+encodeURIComponent(siteId)+'">
<\/script>')
</script>
This is the equivalent of writing
<script type="text/javascript">
var siteId = "VT0013";
</script>
<script type="text/javascript" src="http://www.domainame.com/tracker.php?siteId=VT0013"></script>
Edited to properly escape JavaScript variable.
Please note that it is not advisable to use document.write to load scripts from a third-party domain because Google Chrome might choose not to load the script if the connection is too slow. See https://developers.google.com/web/updates/2016/08/removing-document-write.
If the script can be loaded asynchronously, I recommend this method instead because it will not slow down the HTML parser:
<script>
var siteId = "VT0013";
(function(d, s){
s = d.createElement("script");
s.src = "http://www.domainame.com/tracker.php?siteId="+encodeURIComponent(siteId);
d.getElementsByTagName("head")[0].appendChild(s);
})(document)
</script>

Related

Loading dynamic javascript

I got problem loading dynamic JS in my script, so here the case, I have a plan to build android app with local webview something like webView.loadUrl("file:///android_asset/filename.html");
Everything work fine since its only html file, but the problem came when I need to read local js contain array data that need to read by other js file.
To make it clear,
I have 100++ data_1.js data_2.js etc who contain something like
data = [{
no1:"xxx",
no1:"xxx",
no3:"xxx",
..
}]
Those data will be read by one of my js script and display it on html file, basically I only need 1 data each time the page open, so its like when I open file://.../folder/file.html?no=1 it will only need to read data_1.js, file://.../folder/file.html?no=2 it will only need to read data_2.js
This is what I try to do.
#1
Using getScript("assets/data/data_"+number+".js");
This work when we use local server, when I access via localhost/folder/file.html?no=1 its work, but when I access file://..../folder/file.html?no=1 it not load because cors block
#2
Using ajax, result same with #1
#3
Add all data_x.js directly in file.html
<script src="folder/data_1.js"></script>
<script src="folder/data_2.js"></script>
<script src="folder/data_3.js"></script>
Its work when we access file://..../folder/file.html?no=1 but the page load very slow because need to include and load whole data_x.js (more than 100++)
Is there any other way to solve this problem?
Note: I don't want to connect to any server because I want the apps can be access offline so all data will be included inside the apps
You can make use of URLSearchParam in combination with createElement, which is similar to your solution #3 but only loads the file from parameter id.
So you can also make use of: webView.loadUrl("file:///android_asset/filename.html?id=N");
<html>
<body>
<script>
const urlParams = new URLSearchParams(window.location.search),
id = urlParams.get('id');
if (id != null) {
const script = document.createElement("script");
script.src = `folder/data_${id}.js`;
script.onload = function() {
// do something ...?
}
document.body.appendChild(script);
}
</script>
</body>
</html>
EDIT:
At least at desktop it works fine.

JavaScript function is loaded via Ajax but not executed?

I have different websites that have the same data protection. So that the text does not have to be changed every time on all pages, there is a file on another server that is integrated via Ajax.
There is a part where you can set an opt-out and the domain of the respective page must be stored there.
I don't want to get tracked!
<script type="text/javascript">
document.getElementById("setOptOut").addEventListener('click', function(e) {
e.preventDefault();
var redirect = 'https://' + window.location.hostname + '/privacy';
var url = encodeURIComponent(redirect);
location.href = url;
});
</script>
The code above which is in an HTML file is loaded successfull via Ajax into the document of the web page, but when I click on the link the function is not executed.
If I call the HTML file directly on the server, everything works as expected. Why doesn't it work with Ajax?
Found this good example: https://subinsb.com/how-to-execute-javascript-in-ajax-response/
I used eval() to make the code in the AJAX response execute.

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.

What's the simplest <script> tag with params

I want to include a script tag, while providing a parameter to it. This is what I came up with so far
Provide a parameter to script URL (cons: generate multiple JS files)
<script src="http://example.com/something.js?P=123" type="text/javascript"></script>
Hide parameter in script tag (cons: same as #1)
<script src="http://example.com/scripts/123/something.js" type="text/javascript"></script>
Google Analytics way (cons: ugly, complicated, global variables)
<script type="text/javascript" charset="utf-8">
var _something = _something || 123;
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'http://example.com/something.js';
var ss = document.getElementsByTagName('script')[0];
ss.parentNode.insertBefore(s, ss);
})();
</script>
The best thing is to define things (functions &c) in the external script but execute nothing. Then have an inline script that calls functions/methods defined in the external script.
<script src="http://example.com/something.js" type="text/javascript"></script>
<script type="text/javascript">
something(123);
</script>
If the way the script is executed, depends on how it's called, you can add params like your option 1.
Other ways are:
<script params='{"abc": 123}' src="script.js"></script><!-- params is a non standard, non official attr that the script will read -->
or
<script>var _abc = 123;</script>
<script src="script.js"></script>
or even
<script src="script.js#abc=123"></script>
I have to agree with #outis though: load the same thing for everybody, always, and execute it like you/the client want(s) afterwards.
I do this for a cross-sub-domain XHR handler that I have. I call it as:
<script type="text/javascript" src="xd.js#subdomain"></script>
and then in the script, parse it as such (using jQuery):
$('script').each(function(){
if((src = this.src).indexOf('xd.js') < 0){ return; }
xds = src.substr(src.indexOf('#') + 1).split(',');
// do stuff with xds
});
Your first example does not need to generate multiple files. It can be used by JavaScript alone, by detecting window.location.href and parsing it (you might find the likes of http://phpjs.org/functions/parse_url:485 and http://phpjs.org/functions/parse_str:484 helpful in doing this: var queryString = parse_str(parse_url(window.location.href).query); ).
However, if you use something like #P=123 instead of ?P=123, you won't cause another download of the file by your users, so I'd recommend that instead (in which case change "query" in the above code sample to "fragment").
Another possibility is using the HTML5-reserved data-* attributes, and detecting their values within your script:
<script src="http://example.com/something.js" data-myOwnAttribute="someValue" data-anotherCustomAttribute="anotherValue"></script>
The script would then detect along these lines:
(function () {
function getScriptParam (attr) {
var scripts = document.getElementsByTagName('script'),
currentScript = scripts[scripts.length-1];
return currentScript.getAttribute('data-' + attr); // in future, could just use the HTML5 standard dataset attribute instead: currentScript.dataset[attr]
}
var myOwnAttribute = getScriptParam('myOwnAttribute');
// ... do stuff here ...
}());
The real advantage of Google's ugly API is that it allows developers to drop in that code in the <head> of the document (considered proper form), while still acting asynchronously in a cross-browser way. I think they could indeed avoid the global had they combined their dynamic script-tag technique with either of the above approaches.

XMLHttpRequest() and Google Analytics Tracking

I have implemented an XMLHttpRequest() call to a standalone html page which simply has an html, title & body tag which Google Analytics Tracking code.
I want to track when someone makes a request to display information (i.e. phone number) to try and understand what portion of people look at my directory versus obtaining a phone number to make a call.
It is very simple code:
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "/registerPhoneClick.htm?id=" + id, false);
xhReq.send(null);
var serverResponse = xhReq.responseText
Yet I cannot see the "hit" in Analytics... Has anyone had this issue? All the analytics tracking code does is call:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-XXXXXXX");
pageTracker._trackPageview();
} catch(err) {}</script>
So realistically, my XmlHTTPRequest() calls an htm file within which a script is execute to make an outbound call to Google Analytics.
Is there any reason why an XmlHTTPRequest() would not execute this?
Does an XmlHTTPRequest() still bring the code to the client before execution?
Help Please
Requesting the file doesn't mean that it's automatically executed. You just get the content of the file back as a string.
For the code to be executed, it would have to be loaded as a page in the browser. You can for example use an iframe to load it.
To those having similar issues, obviously analytics won't track XMLHttpRequest() so to get around it, I found this post: Tracking API: Basic Configuration which explains how to simply log a pageview using javascript.
I simply added the following code to my javascrip:
var pageTracker = _gat._getTracker("UA-XXXXX-XXX");
pageTracker._trackPageview("/home/landingPage");
Much cleaner, easier and simpler than what I was originally trying to do...

Categories

Resources