Javascript: reload page with changed variable value - javascript

Is it possible to change variable "a" to "true" without modifying the page source, so that it prints "foo"?
<html>
<head>
<script>
var a = false;
if(a) document.write("foo");
else document.write("bar");
</script>
</head>
<body>
</body>
</html>
I can change variable value dinamically from Chrome. But how to reload to see "foo", not "bar"

How should this work? You cannot preserve a state on reload with a static HTML page and an embedded script. Use a cookie or some other persistent mechanism for storing the state.

You can use localstorage on most modern browsers see http://www.w3schools.com/html/html5_webstorage.asp
if you plan to support older browsers, you can set a cookie then read it when the document reloads.
http://www.w3schools.com/js/js_cookies.asp
edit: Try this code
//function to check support for localStorage
function checkLocalStorageSupport() {
try {
localStorage.setItem("x", "x");
localStorage.removeItem("x");
return true;
} catch (e) {
return false;
}
}
//function to read value of cookie
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
if (checkLocalStorageSupport()) {
if (localStorage.getItem('a') != null)
if (localStorage.getItem('a') == "true") //check that the value of localStorage is not null
document.write("foo"); //do operation if localStorage value is true
else
document.write("bar");
else
localStorage.setItem('a', 'false');
}
else {
if (getCookie('a') != null) //check that the value of cookie is not null
if (getCookie('a') == "true")
document.write("foo"); //do operation if cookie value is true
else
document.write("bar");
else
document.cookie = "a=false; expires=Thu, 31 Dec 2015 12:00:00 UTC"; //if no cookie exists set a cookie
}

Related

Manual swith back to normal Website on mobile Device using wurfl

I can't get into it. Please give me a hint.
There is a website with device-detection with wurfl - the javascript method.
The condition looks like this:
if(!WURFL.is_mobile){
$('body').addClass('mobile'); //Do the stuff for mobile website
} else {
$('body').addClass('no-mobile'); // Do the stuff for no-mobile normal website
};
Now we want to put a button on mobile Version to switch back to normal (no-mobile) Website manualy. But the website needs to be reloaded without care of the orginal wurfl-condition, because there are some images and html inserted with javascrit on the normal (no-mobile) Version. I don't know how to do this.
When the button is pressed to manually go to mobile or desktop, you can set a cookie like so:
document.cookie = "forceMobile=true";
then just read the cookie in your if statement like so:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if(!WURFL.is_mobile && !getCookie("forceMobile")) ...
More info here

Third party cookie to check if the browser block it by default

I want to check which browser blocks by default third party cookie.
I though to create a local file .html with a third party cookie and open it to every browser to check it will open. Is this a good option?
I plan to use this example but is it a third party cookie?
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
This code will create a 1st party cookie - i.e. the domain of this cookie will match the domain of the page loaded.
In order to create a third party cookie you must request a resource from a different domain than the page that requests that resource. This resource could set a cookie using either javascript or HTTP header command (which is initiated by server side code like PHP).
If you are just doing your own survey to gain information about which browsers accept 3rd party cookies by default then it may be worthwhile looking at the specification for each browser to see what the official line is before going to the effort of testing.

JavaScript EU cookie law banner not removing

I've been trying to add a EU cookie policy banner to my website. The javascript code below inserts the banner (once I add a small bit of styling) but when I click on the "x" to close the banner and hopefully hide it for future visits, nothing happens. The banner doesn't disappear.
Can anyone tell me why this isn't working? Javascript is not my strong point!
//Cookie banner
var dropCookie = true; // false disables the Cookie, allowing you to style the banner
var cookieDuration = 14; // Number of days before the cookie expires, and the banner reappears
var cookieName = 'complianceCookie'; // Name of our cookie
var cookieValue = 'on'; // Value of cookie
function createDiv(){
var bodytag = document.getElementsByTagName('body')[0];
var div = document.createElement('div');
div.setAttribute('id','cookie-law');
div.innerHTML = '<p>Our website uses cookies. By continuing we assume your permission to deploy cookies, as detailed in our privacy and cookies policy. <a class="close-cookie-banner" href="javascript:void(0)" onclick="removeMe()"><span>X</span></a></p>';
// Be advised the Close Banner 'X' link requires jQuery
// bodytag.appendChild(div); // Adds the Cookie Law Banner just before the closing </body> tag
// or
bodytag.insertBefore(div,bodytag.firstChild); // Adds the Cookie Law Banner just after the opening <body> tag
document.getElementsByTagName('body')[0].className+=' cookiebanner'; //Adds a class tothe <body> tag when the banner is visible
createCookie(window.cookieName,window.cookieValue, window.cookieDuration); // Create the cookie
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
if(window.dropCookie) {
document.cookie = name+"="+value+expires+"; path=/";
}
}
function checkCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)===' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
window.onload = function(){
if(checkCookie(window.cookieName) !== window.cookieValue){
createDiv();
}
};
function removeMe(){
var element = document.getElementById('cookie-law');
element.parentNode.removeChild(element);
};
Thanks!
The function removeMe is undefined in the current scope of the onclick handler. To fix this, you should replace this line function removeMe() { with window.removeMe = function removeMe() {.
Live example (with formatted code): https://jsfiddle.net/xnhpzto8/1/

JS to redirect to a splash page on first visit?

I'm trying to modify some code to direct users to a "create an account" squeeze page on their first visit. I think I'm close, but I need a little help. Any advise on where I went wrong?
<script type="text/javascript">
$(document).ready(function() {
// check cookie
var visited = $.cookie("visited")
if (visited == null) {
window.location = "content/content-article.asp?ArticleID=4998"
$.cookie('visited', 'yes');
alert($.cookie("visited"));
}
// set cookie
$.cookie('visited', 'yes', { expires: 10,000, path: '/' });
});
OK - I kept digging and found a different script that worked. Here it is in case someone else is trying to do the same thing:
<script type="text/javascript">
function redirect(){
var thecookie = readCookie('doRedirect');
if(!thecookie){window.location = 'http://yournetwork.com/splash';
}}function createCookie(name,value,days){if (days){var date = new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires = "; expires="+date.toGMTString();}else var expires = "";document.cookie = name+"="+value+expires+"; path=/";}function readCookie(name){var nameEQ = name + "=";var ca = document.cookie.split(';');for(var i=0;i < ca.length;i++){var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length);if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);}return null;}window.onload = function(){redirect();createCookie('doRedirect','true','999');}
Try this:
$(document).ready(function() {
// check cookie
var visited = $.cookie("visited")
// set cookie
$.cookie('visited', 'yes', { expires: 10,000, path: '/' });
if (visited == null) {
$.cookie('visited', 'yes');
alert($.cookie("visited"));
window.location = "content/content-article.asp?ArticleID=4998"
}
});
Change the location to another site AFTER executing your code

How to run script only when user land on page

I have some script, written in Javascript, that show progress of loading site elements. I put this script on index.html file, so it runs only on main page. It works perfectly fine, but now it show progress when you land on index.html and also when you come back to main page from subpage which is my problem because main page is already cached and it's waste of time.
My question is: How to run script only when user land on page, not when he come back from subpage?
Try cookies to control when/when not to execute Javascript.
Create a cookie when the user hits index.html for the first time. Check for the cookie and only run the script if the cookie hasn't been set.
if(!isset($_COOKIE['something'])) {
// run your loading script;
setcookie('something','someValue');
}
Just be sure you have the above code before sending any output to the browser.
In addition to cookies you can use document.referrer:
<script>
if(document.referrer &&
document.referrer.indexOf("yoursite.com") == -1)
{
// Page loading process script goes here.
}
</script>
<html>
<head>
..
</head>
<body onload="doStuff()">
...
<script type="text/javascript" language="JavaScript">
//<![CDATA[
function doStuff(){
//check condition
if (readCookie('checkFirstTime')!=null) return;
//otherwise set the flag && do your thing
createCookie('checkFirstTime','yep',1);
alert("Welcome home Yo!");
...
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
//]]>
</script>
...
</body>
</html>

Categories

Resources