IE not liking URL variable? [duplicate] - javascript

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 5 years ago.
Hey guys, I have this quite simple script which works great on chrome & firefox.
The idea is to nab "choice" value from the URL and proceed with the script. As mentioned other browsers work fine, but IE seems to have trouble with it.
Does anyone know a workaround? I don't want to just run the function on the previous page.
var url1 = "https://www.youtube.com";
var url2 = "http://ign.com";
function jukebox()
{
let params = (new URL(document.location)).searchParams;
let choice = params.get("choice");
if ( choice == 1 )
{
window.location=(url1);
}
else if ( choice == 2 )
{
window.location=(url2);
}
}
jukebox();
redirect();

IE does not support searchParams but you could try writing your own parse function:
var params = {};
var str = document.location;
var start = str.indexOf("?");
document.write(start+"<br>")
start += str.slice(start).indexOf("choice=") + 7;
var end = start + str.slice(start).indexOf("&") + 1;
if (!end) end = str.length
var choice = str.slice(start, end);

Related

How can I store part of the current URL in javascript? [duplicate]

This question already has answers here:
How do I get the fragment identifier (value after hash #) from a URL?
(8 answers)
Closed 3 years ago.
I am trying to create a web app that uses a zip code (passed from the previous page). The URL looks like /location#12345
I am trying to store everything after '#' in a variable to be used in the location finder app.
URL: /locations#12345
$(document).ready(function(){
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("#");
var myVal;
for (var i = 0; i < queries.length; i++)
{
myVal = myVal + queries[i];
}
alert(myVal);
});
I thought alert(myVal) would produce "12345" but it is blank. There are no errors in the console.
For a single hash String.split() is enough:
Working demo
const str = '/locations#12345UR';
const hash = str.split('#')[1];
alert(hash);

Display a JavaScript variable in a page loaded in innerHTML [duplicate]

This question already has answers here:
Load scripts inside innerHTML [duplicate]
(2 answers)
Closed 4 years ago.
I have an HTML page that loads within another HTML page via innerHTML. After several days of work, this script works fine and another JS file is called for the interior page, a file (named "Unified_app.js") that basically runs some date calculations. Everything is working fine and the correct dates print to the console. However, I can't figure out on the page within a page can display the console dates. Document.write does not work in this situation (I'm assuming because of the tags are not read properly?), so I need to come up with a workaround. Any ideas?
This is the innerHTML functions as I have them:
function getYearOffset(strCutoffDate, intYearOffset)
{
var datCurrentDate = new Date();
var intCurrentYear = datCurrentDate.getFullYear();
var intCurrentMonth = strCutoffDate.substr(5, 2) - 1;
var intCurrentDay = strCutoffDate.substr(8, 2);
var datCutoffDate = new Date(intCurrentYear, intCurrentMonth, intCurrentDay);
if (Number(datCurrentDate) < Number(datCutoffDate))
{
var datRequestedDate = new Date(datCurrentDate.getFullYear(), intCurrentMonth, intCurrentDay);
}
else
{
var datRequestedDate = new Date(datCurrentDate.getFullYear() + intYearOffset, intCurrentMonth, intCurrentDay);
}
return datRequestedDate.getFullYear();
}
var script = document.createElement("script");
script.src = "/resource/resmgr/scripts/Unified_app.js";
document.head.appendChild(script);
function getInclude(strIncludeContainer, strIncludeURL)
{
var strPage = '';
var intIndexOfBodyOpen = 0;
var intIndexOfBodyClose = 0;
var objXhttp;
objXhttp = new XMLHttpRequest();
objXhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
strPage = this.responseText;
intIndexOfBodyOpen = strPage.indexOf('<body>');
intIndexOfBodyClose = strPage.indexOf('</body>');
document.getElementById(strIncludeContainer).innerHTML = strPage.substring(intIndexOfBodyOpen + 6, intIndexOfBodyClose);
}
};
objXhttp.open("GET", strIncludeURL, true);
objXhttp.send();
}
I'm using:
<script>document.write(award_year1);</script>
to write the following date calls:
const date = new Date();
let offset = 0;
const threshold = new Date();
threshold.setMonth(3); //January is 0!
threshold.setDate(3);
if (Date.now() > threshold) {
offset = 1;
}
var theDate = new Date();
var award_year1 = date.getFullYear() + offset;
var award_year2 = date.getFullYear() + 1 + offset;
console.log(award_year1);
console.log(award_year2);
When loading the page-within-a-page HTML file or the interior page itself I get the correct date calculations sent to the console, but I can't seem to get them to print within the innerHTML page when loaded into the other page. Any ideas you could send me down the right path? This is probably beyond my level of understanding of JavaScript. I thought perhaps my code was not in the correct order but I've been fiddling with this and can't seem to figure out where or why.
I'm not sure if this will solve the problem but you can try it.
As you said the document.write will not be triggered cause your JS is loaded before your DOM is.
document.addEventListener("DOMContentLoaded", function(event) {
//your functions
});
Maybe this will help you out
I guess this is just not possible. I ended up replacing the innerHTML with an iframe and that seems to have worked so that I can now use script tags. Not an ideal solution but it works

In this example how would I make filenames appended with "0000"+1 instead of "0"+1? [duplicate]

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 8 years ago.
I know this is a gimme, but I'm trying to make the filenames serialized with four digits instead of one. This function is for exporting PNG files from layers within Adobe Illustrator. Let me know if you ever need icons - much respect.
var n = document.layers.length;
hideAllLayers ();
for(var i=n-1, k=0; i>=0; i--, k++)
{
//hideAllLayers();
var layer = document.layers[i];
layer.visible = true;
var file = new File(folder.fsName + '/' +filename+ '-' + k +".png");
document.exportFile(file,ExportType.PNG24,options);
layer.visible = false;
}
Use util.printf (see the Acrobat API, page 720):
var file = new File(util.printf("%s/%s-%04d.png", folder.fsName, filename, k));
You can pad your number to the left and take the last four characters like this:
var i = 9;
var num = ("0000"+i);
var str = "filename"+(num.substring(num.length-4)); //filename0009
Or shorter
str = ("0000" + i).slice(-4)
Thanks to this question

getting parameter from url [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Get escaped URL parameter
(19 answers)
Closed 9 years ago.
I have this url index.html#secondPage?name=the%20second%20page
I want to get the value of name ("the second page") using javascript and jquery
thanks
You can use the code from the answers to this question. The only difference is that you want to parse the location.hash instead of location.search so just change that in whichever answer you choose to go with.
You'll also need to use substr to delete the leading # like:
var hash = window.location.hash.substr(1);
Here is the code from my answer to the question I linked to, with the modification:
function get_query(){
var url = location.hash.substr(1);
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
You can use it like:
var secondPage = get_query()['name']; // 'the second page'
Try like below, It will help you
Fiddle : http://jsfiddle.net/RYh7U/144/
Javascript :
function GetURLValue (sKey) {
return unescape("index.html#secondPage?name=the%20second%20page".replace(new RegExp("^(?:.*[&\\?]" + escape(sKey).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(GetURLValue("name"));

How to prevent storing domain name in href = $('a#myId').attr('href'); in IE7 [duplicate]

This question already has answers here:
Wrong extraction of .attr("href") in IE7 vs all other browsers?
(7 answers)
Closed 8 years ago.
For example if
location.href = 'http://mydomain.com/en/'
and I have
i am just a link
so
href = $('a#id').attr('href');
for some reason Firefox, Chrome and Opera return: my-file.html
but IE7 will return: http://mydomain.com/en/my-file.html
I tried this function with the domain-name but gives an error:
function str_replace(busca, repla, orig)
{
str = new String(orig);
rExp = "/"+busca+"/g";
rExp = eval(rExp);
newS = String(repla);
str = new String(str.replace(rExp, newS));
return str;
}
domain-name is not defined
[Detener en este error] rExp = eval(rExp);
Any ideas for how to prevent it???
Try following :
//this will give you filename only
var chk = "http://mydomain.com/en/test.html";
var chkArr = chk.split("/");
var filenameOnly = chkArr.pop();
Hope it helps
You should avoid using eval in your code.
You can use str = str.replace(/.*\//, ''); to strip everything before the last / in a string.

Categories