Javascript not working on simple test page - javascript

I'm trying to test my local storage so I've tried a few examples.
this example worked before but now its not. not sure what happened
https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/
Now I am trying this code and nothing pops up on if else, it just says local storage is
function lsTest() {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
var elem = document.getElementById('status');
if (lsTest() === true) {
elem.innerHTML += 'available.';
} else {
elem.innerHTML += 'unavailable.';
}
html
<div id="status">Local Storage is </div>
full code
http://tny.cz/39896a73

You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access.

Try this, using a webserver as Nimrodx said.
window.onload = function(){
function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
console.log(e);
return false;
}
}
var elem = document.getElementById('status');
if(lsTest() === true){
elem.innerHTML += 'available.';
}
else{
elem.innerHTML += 'unavailable.';
}
};

There is no issue with your method, but I didn't see any call to this method.
To make it functional, you need to call it with some event. Like: button / anchor onlick, window load / ready as following:
Javascript:
window.onload = function(){lsTest();}
jQuery:
jQuery(document).ready(function(){
lsTest();
});
DEMO
However, if you just want to check the browser compatibility of localStorage / sessionStorage then if(typeof(Storage) !== undefined){} is quite useful.

Related

Google Tag Manager Custom Variable return Undefined

I'm working with Google Tag Manager using a Custom JS Variable to store data about user's privacy consent.
I tried the function below with a variable for privacy that is set to true only if the user clicks on a specific button.
function controlloConsenso() {
var privacyAccettata = false;
var checkPrivacy = document.querySelector(".ginger_btn_accept_all");
checkPrivacy.addEventListener("click", function() {
privacyAccettata = true;
});
return privacyAccettata;
}
The problem is that the variable result is undefined within the GTM Debugger.
When trying the script outside the first function (that GTM doesn't accept) the code works fine (I've tested it in Chrome Console).
var privacyAccettata = false;
var checkPrivacy = document.querySelector(".ginger_btn_accept_all");
checkPrivacy.addEventListener("click", function() {
privacyAccettata = true;
});
Omit the name from your function and it should work. That is, change your custom JavaScript tag to:
// function controlloConsenso() {
function(){
var privacyAccettata = false;
var checkPrivacy = document.querySelector(".ginger_btn_accept_all");
checkPrivacy.addEventListener("click", function() {
privacyAccettata = true;
});
return privacyAccettata;
}

how to remember clicked href and redirect to it javascript

My home page has a couple of links: one for English version and the other for French version. Something like this:
<a class="ensite" href="/en">English</a>
<a class="ensite" href="/fr">French</a>
I want to use JavaScript to remember the last choice made by visitors and when they come again, they don't have to choose the language one more time because I want them to be autoredirected to the preferred language using cookies.
P.S. the visitors are strangers, not registered users. I want to store cookies in visitors' browsers, not in the database. Please, help me by providing me with the full solution.
Gelerally, the idea is: set handlers on links and upon clicking save preferred version into localStorage. Then every time user loads any page of your site, just check, whether the url contains the language context ("en"/"fr") the user chose before. If yes - do nothing, user opened the right version; if not - redirect him to the previously saved version. The following is a Vanilla approach (not properly tested). You will have to tweak it (attachEvent etc.) or use jQuery library to implement similar ideas in a shorter and more cross-browser way.
<a class="ensite" href="/en">English</a>
<a class="ensite" href="/fr">French</a>
JS:
function LanguageManager(selector) {
this.langLinks = document.querySelectorAll(selector);
}
LanguageManager.prototype.setHandler = function() {
var self = this;
this.langLinks.forEach(function(langLink) {
langLink.addEventListener("click", self.handler, false);
});
}
LanguageManager.prototype.redirect = function() {
var link = storageManager.restoreDataFromStorage();
if(link && !~window.location.href.indexOf(link)) window.location.href = link;
}
LanguageManager.prototype.handler = function() {
var e = event || window. event;
var elem = e.target || e.srcElement;
if(e.preventDefault) e.preventDefault(); else e.returnValue = false;
storageManager.saveDataToStorage(elem.href);
location.href = elem.href;
}
function StorageManager() {
this.storageName = "languageVersion";
this.storageData = null;
}
StorageManager.prototype.isStorageAvailable = function(type) {
try {
var storage = window[type], x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
} catch(e) { return false; }
}
StorageManager.prototype.saveDataToStorage = function(data) {
if(!this.isStorageAvailable('localStorage')) {
this.storageData = data;
return false;
}
try {
localStorage.setItem(this.storageName, JSON.stringify(data));
return this.storageName;
} catch(e) {
this.storageData = data;
return false;
}
}
StorageManager.prototype.restoreDataFromStorage = function() {
if(this.storageData) return this.storageData;
return JSON.parse(localStorage.getItem(this.storageName));
}
var storageManager = new StorageManager();
var languageManager = new LanguageManager(".ensite");
languageManager.setHandler();
languageManager.redirect();
Also notice, that there may be issues depending on how you implement language contexts on your site. You can start with my code on your own and tweak it or find someone else to get this properly done.
Just tested this, it works perfect.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<a class="ensite" href="" onclick ="localStorage.setItem('language','en')">English</a>
<a class="ensite" href="" onclick = "localStorage.setItem('language','fr')">French</a>
<script>
$(document).ready(function(){
var language = (localStorage.getItem('language') == null)? 'en' : localStorage.getItem('language');
console.log(language);
})
</script>

Make fullscreen API code work cross browser

On my page I have following code, which I use for making some object a full screen one
<script>
$(document).ready(function(){
$('.fs-button').on('click', function(){
var elem = document.getElementById('fullscreen');
if (document.webkitFullscreenElement) {
document.webkitCancelFullScreen();
} else {
elem.webkitRequestFullScreen();
};
});
});
</script>
Problem is its working only in Chrome. Can you please give me cross browser version of this code? Cannot do this by myself because of poor JS knowledge.
You can use this.
Reference : https://msdn.microsoft.com/en-us/library/dn265028(v=vs.85).aspx
// Initiated by a user click on an element
function makeFullScreen(divObj) {
//Use the specification method before using prefixed versions
if (divObj.requestFullscreen) {
divObj.requestFullscreen();
}
else if (divObj.msRequestFullscreen) {
divObj.msRequestFullscreen();
}
else if (divObj.mozRequestFullScreen) {
divObj.mozRequestFullScreen();
}
else if (divObj.webkitRequestFullscreen) {
divObj.webkitRequestFullscreen();
} else {
console.log("Fullscreen API is not supported");
}
}
once after writing that function, you just need to call inside click event handler as..
$(document).ready(function(){
$('.fs-button').on('click', function(){
var elem = document.getElementById('fullscreen');
//call that function to make it fullscreen.
makeFullScreen( elem );
});
});

How to execute Javascript alert when page loads the first time only

I am trying to execute a javascript alert, but only alert if it is the first time that browser / computer has viewed that page - or something similar to that.
How would this be done? I have written the Javascript to what I think it be similar to.
function alert() {
alert(" Please view this is Firefox");
}
if (first time viewing this page) {
alert();
}
I really appreciate your help
You could use the JQuery Cookie Plugin for this.
function showPopUp() {
var cookie = $.cookie('the_cookie');
if(!cookie){
alert(" Please view this in Firefox");
$.cookie('the_cookie', 'the_value');
}
}
showPopUp();
You can use localStorage or cookies:
Here is an example with localStorage:
var visited = localStorage.getItem('visited');
if (!visited) {
alert("Please view this is Firefox");
localStorage.setItem('visited', true);
}
Don't use a Cookie it will be sent to the server at each time your make request. You can use Local Storage instead, like:
function load() {
var isFired = localStorage.getItem('checkFired');
if (isFired != '1'){
alert(" Please view this is Firefox");
localStorage.setItem('checkFired', '1');
}
}
load();
See this link you will get some idea example is based on cookies...Once you typed you value and if you refresh it, it will show the value..
Set cookie
document.cookie="first=first";
Read a Cookie with JavaScript
var x = document.cookie;
Example:
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie()
{
var first=getCookie("first");
if(first == "first")
{
alert(" Please view this is Firefox");
}else{
document.cookie="first=first";
}
}
Cookie in JS

javascript detect if being run in hta

We'd like to allow our users to download an hta file and run our web app inside it, and have certain pages detect that they are running in an hta file and offer additional features that a web app wouldn't normally have permission to do.
How can I simply detect if the page is being browsed from an hta file container?
window.location.protocol=='file:' would indicate a local page but that could be a local
html page or a local hta.
I'm thinking window.external may be different in each context.
So making and opening a.htm and a.hta containing:
<script>document.write(window.external)</script>
We get:
IE: [object]
FireFox: [xpconnect wrapped (nsISupports, nsISidebar, nsISidebarExternal, nsIClassInfo)]
Chrome: [object Object]
HTA: null
So, isHTA=(window.external==null) would indicate the HTA context.
Or, isHTA=false;try{isHTA=(window.external==null)}catch(e){}
To be on the safe side, since I have only tested current versions of IE, FF, and Chrome and who knows what the other browsers will do.
What about just:-
var isHTA = (document.all && top.document && (top.document.getElementsByTagName('application')[0]));
HTAs are unique in how they populate the DOM with the <HTA:APPLICATION> tag. I use the following to grab the HTA object:
var hta;
var elements = document.getElementsByTagName("APPLICATION");
for(var i=0; i<elements.length; i+=1) {
if ("hta" === elements[i].scopeName.toString().toLowerCase()) {
hta = elements[i];
break;
}
}
// To test if the page is an HTA:
var isHta = (undefined !== hta);
In other browsers, you will have to use the full tag name to access the same object:
// For Firefox/Chrome/IE
var elements = document.getElementsByTagName("HTA:APPLICATION");
I haven't tested, but wouldn't just looking at window.location work?
This might fit the bill. Verifying the attributes could be removed.
<hta:application id="myHTA"/>
<script>
alert("isHTA = " + isHTA("myHTA"));
function isHTA(htaId) {
var retval = false;
var hta = window[htaId];
if (!hta) {
// hta wasn't defined
} else if (hta.scopeName != "hta") {
// hta:application
} else if (hta.nodeName != "application") {
// hta:application
} else if (hta.tagName != "application") {
// hta:application
} else {
retval = true;
// attributes only a real hta would have
var attribKeys = [
"applicationName",
"border",
"borderStyle",
"caption",
"commandLine",
"contextMenu",
"icon",
"innerBorder",
"maximizeButton",
"minimizeButton",
"scroll",
"scrollFlat",
"selection",
"showInTaskBar",
"singleInstance",
"sysMenu",
"version",
"windowState"
];
for (var i=0;i<attribKeys.length;i++) {
var attribKey = attribKeys[i];
if (!hta.attribKey === undefined) {
retval = false;
break;
}
}
}
return retval;
}
</script>
Checking the commandLine property of the HTA-Application object is the best method to see if you are running as real HTML-Application, because this property is only available in the mshta.exe.
You need to get the HTM-Application object to check this property. If you don't know the ID of the object you can use this code:
// Check if running in a HTML-Application
var isHTA = false;
var htaApp = document.getElementsByTagName("HTA:APPLICATION")
if (!htaApp.length) {
htaApp = document.getElementsByTagName("APPLICATION");
}
if (htaApp.length == 1 && htaApp[0]) {
isHTA = typeof htaApp[0].commandLine !== "undefined";
}
guess not many people still using HTA nowadays, anyway, I think the below should cover all the scenarios:
<script language=javascript>
var VBScriptVersion = "";
function getVBScriptVersion() {
var firstScriptBlock = document.getElementsByTagName('script')[0];
var tmpScript = document.createElement('script');
tmpScript.setAttribute("language", "VBScript");
tmpScript.text = 'VBScriptVersion = ScriptEngineMajorVersion & "." & ScriptEngineMinorVersion';
tmpScript.async = false;
tmpScript.onload = function() {
this.parentNode.removeChild(this);
}
firstScriptBlock.parentNode.insertBefore(tmpScript, firstScriptBlock);
return VBScriptVersion;
}
var isHTA = (getVBScriptVersion()!="" && window.external==null);
</script>

Categories