Can you pass URL parameters to a Javascript file? - javascript

<script src="myscript.js?someParameter=123"></script>
From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?

Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.
There are two ways to pass parameters to another JavaScript file:
As #Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.

Jquery Address does this, so i've been checking their code out and this is the improved solution I just created myself:
$.each($('script'), function(id, val){ //loop trough all script-elements
var tmp_src = String($(this).attr('src'));//store the src-attr
var qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index
//Check if the script is the script we are looking for and if it has QS-params
if(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
{
//this is myscript.js and has a querystring
//we want an array of param-pairs: var1 = value1, var2 = value2, ...
var params_raw = tmp_src.substr(qs_index + 1).split('&');
//create empty options array
var options = [];
//loop troug raw params
$.each(params_raw, function(id, param_pair){
//split names from values
var pp_raw = param_pair.split('=');
//store in options array
options[pp_raw[0]] = pp_raw[1];
});
//check the results out in the console!
console.log(options);
}
});
I hope this does what you need?

The answer is a definite "YES". I've been doing this on various projects for over a decade. The solution is actually easy, it's just non-intuitive (you have to generate an error). To be clear, the following code lets you do something like this:
<script src="https://example.com/script.js?id=1&bar=this works!" />
All you need to do is initiate a silent error, which takes less than 1/1000 of a second even on the worst outdated mobile browsers. You shouldn't do it a ton, but you only need to do it once. This error is processed, so it won't show up as an error in telemetry or 3rd party error trackers either.
// Generic function used to see if a param exists in a URL string.
// Provided here in case you don't know how to do it.
// This is not needed for the solution.
function getParameter (name, url) {
if (!url) url = scriptName()
name = name.replace(/[\[\]]/g, '\\$&')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
var results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
// Gets the name of this script (whatever this file runs in)
// You can use this name to get parameters just like you would for the window URL :)
function getScriptName () {
var error = new Error(),
source,
lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/),
currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/)
if ((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] !== '')
return source[1]
else if ((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1]
else if (error.fileName !== undefined)
return error.fileName
}

Related

Why Blogger URL Related Post Undefined

I create a function using Javascript for related post on my Blogger template,
Here is my code:
function toHttps(link) {
var protocol=link.replace(/\:/g,'');
if(protocol=='http') {
var url=link.replace('http','https');
return link.replace(url);
}
}
if my original url is
https://dpawoncatering.blogspot.com/2008/08/nasi-box-murah.html
Why is the result like this?
https://dpawoncatering.blogspot.com/2008/08/undefined?
Naren Murali's answer is correct. I'd just like to add a different way of doing "protocol" swap using javascript's own URL parser that might be interesting for other people.
You can instantiate an a element and use its href attribute to parse your URL, then you can access and change the protocol attribute of the href and retrieve the resulting URL:
function toHttps(link) {
var url = document.createElement('a');
url.href = link;
url.protocol = 'https';
return url.href;
}
Since the URL contains https already it does not enter the if condition, hence nothing is returned hence we get undefined, please check my corrected function. Let me know if you have any issues!
function toHttps(link) {
if(link.indexOf('http://') > -1){
var url=link.replace('http','https');
return url;
}
return link
}
console.log(toHttps('http://dpawoncatering.blogspot.com/2008/08/nasi-box-murah.html'))
console.log(toHttps('https://dpawoncatering.blogspot.com/2008/08/nasi-box-murah.html'))

JavaScript: How to save the state of your website structure to a link (or hash link)

In my website I have some part when you 'click' on it, It will show a (pop-up) div & grays the rest of the website, However I want to make a link/hashlink for that state.. something like this ( http://www.mywebsite.com/show-pop-up ), So whenever my visitors type the link above in their browser and go, They will come to my website with (the pop-up visible).
I saw this in Trello.com & Behance.com (When you click in a project it will show as pop-up with a new link in the browser).
Note: I need this in 'pure' JavaScript.
There are several ways you can achieve this. One of the following options may work for you.
Option 1: using hashes. Consider the following url: www.mywebsite.com/index.html#popup. You can retrieve the #popup value on startup of your website and act accordingly. See the code sample below.
document.addEventListener("DOMContentLoaded", function(event) {
// Website has loaded.
var hash = location.hash
// Check if the hash exists and is popup.
if (hash && hash === 'popup') {
// Show your popup
}
});
Another option would be to use query strings. Consider the following url: www.mywebsite.com?popup=true. First you have to retrieve the query strings, using for example the following function. Afterwards check if the popup querystring has been used.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var popup = getParameterByName('popup');
// Check if we have the popup parameter.
if (popup) {
// Show popup
}
Suggest using
http://www.mywebsite.com#show-pop-up
instead of
http://www.mywebsite.com/show-pop-up
then using
if(location.hash === '#show-pop-up') {
// show your popup
}
on page loaded.

Retrieve URL Parameters Sent Through JQuery .load()

I am not sure if what I'm trying to do is possible or if I'm going about this the right way. In some circumstances I want them to have a GET parameter as part of the URL. I want the receiving page to be able to differentiate whether the sending load has a parameter or not and adjust accordingly.
Here is what I have that is sending the load:
$(document).ready(function () {
$("a").click(function () {
$("div.pageContent").html('');
$("div.pageContent").load($(this).attr('href'));
return false;
});
});
In this case, the load could have "example.php" or "example.php?key=value". In looking around (primarily on this site), I've found things that seem to be close, but don't quite get there. In the page that is getting loaded (example.php), I have the following:
function $_GET(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
$(document).ready(function () {
var URL = "example2.php";
if ($_GET('key'))
{
URL = "example2.php?key=" + $_GET('key');
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
If the sending source includes a query string, I want to add that to the URL and load it in a div that is unique to this page, otherwise I want to just load it as is without the query string. The big issue I'm running into (I believe) is since this is coming from an AJAX call, the "window.location.href" is not what was sent from the JQuery but rather the URL of the root page which never changes. Is there a way to be able to know what the full URL is that was sent from the load() in the first page by the second one?
Thank you in advance for your help.
I realized that the GET parameters were getting passed as I could access them through php without issue. I didn't know that I could insert php code into a javascript block but once I tried it, all worked out. My new code looks like this:
$(document).ready(function () {
var URL = "example2.php";
var myValue = "<?php echo $_GET['key']; ?>";
if (myValue !== "")
{
URL = "example2.php?key=" + myValue;
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
I was able to get rid of the GET function out of javascript entirely. I probably made this much more difficult from the start but hopefully it can help someone else in the future.

Java script URL Loader and URL Varialbles

I have a URL to a text file which specifies what my menu controller is called and whether I am in debug mode etc....
eg. menudriver=MenuController.aspx&debug=true&webroot=https://somewebsite.com
Now what I would like to do is have this loaded into a variable in javascript then also each URL variable also saved into some array.
Once this has been done I have a menu that is dynamically populated according to what is received from a separate URL. Here is an as3 example:
var request:URLRequest = new URLRequest(WebRoot+fill+CallerURI+"?KR_ID="+Math.random());
This URL basically contains labels as well as URI for buttons in my menu.
How is this done is javascript?
I do have a completed implementation in as3 but I am battling to find the javascript alternatives.
in Reply to the comment, pure javascript solution
var query = (function() {
function decode(string) {
return decodeURIComponent(string.replace(/\+/g, " "));
}
var result = {};
if (location.search) {
location.search.substring(1).split('&').forEach(function(pair) {
pair = pair.split('=');
result[decode(pair[0])] = decode(pair[1]);
});
}
return result;
})();
it use ECMAScript 5 function forEach, if you need to support browsers that don't support it, you can use es5-shim.

Pushing data to javascript array but the array is not growing

I'm trying to create a navigation system for an internal website.
To do so I'm creating an array by means of javascript that tracks the url of the page and with each new page I'm pushing that new url into the array.
Problem is, each new page seems to be overwriting the last page.
This is what is in my javascript file ... notice I only create a new array if the array doesn't already exist (it will be deleted when the person leaves the website).
var myURL = document.URL;
if (typeof myHistory == "undefined" || !(myHistory instanceof Array)) {
var myHistory = [];
}
myHistory.push(myURL);
var last_element = myHistory[myHistory.length - 1];
var number_rows = myHistory.length;
This what I'm using to see the values in the html ...
<script type="text/javascript">
<!--
document.write(last_element);
document.write(number_rows);
// -->
</script>
It's displaying the URL (last_element) as desired but number_rows remains at 1 when I browse between pages rather than go up to 2, 3, 4, etc which is what I hope to achieve.
Can anyone give me any pointers?
Every time you refresh a page, JavaScript is refreshed anew. If you need to have data persistence, you'll need to use cookies, localStorage, or server-side data storage.
All of those options will require that you serialize to and deserialize from strings.
Here's a quick example of how you could do this using localStorage:
//closure to prevent global pollution
//it's good to be green
(function () {
"use strict";
var history,
url;
//set url here
//I'm making the assumption that no url will have a ',' char in it
history = localStorage['history'].split(',');
history.push(url);
localStorage['history'] = history.join(',');
console.log(url, history.length);
}());
When you browse between pages the javascript environment is re-created on each page. So you are always starting with an empty array.

Categories