Cookie in Webview android - javascript

I am struggling with using cookie along with javascript in webview android.
I have one HTML page which is located in sdcard data. This html file consist of javasript and cookie. I need to load this html file in webview and webview needs to respond to javascript as well as cookie.
Work done so far:-
Enabled javascript for webview
WebView1.getSettings().setJavaScriptEnabled(true);
Also tried to enable cookie using CookieManager
CookieManager.getInstance().setAcceptCookie(true);
Doing this, webview respond to javascript but not cookies. Any Idea how to solve this problem?
HTML file is as follows
<!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.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var res = "No Cookie!";
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) != -1) res = c.substring(name.length, c.length);
}
document.getElementById('txt').innerHTML = res;
}
</script><noscript>No JavaScript!</noscript>
</head>
<body onload="setCookie('id', 'Cookie is working properly!', '1');">
<p id="txt"> </p>
<center>
Next Page
</center>
</body>
</html>
When i open this File in browser, its working fine. If someone wants to open this file in browser then please use the following url https://www.ypsid.com/demo/test/test-1.html

If you are using Android Lollipop i.e. SDK 21, then:
CookieManager.getInstance().setAcceptCookie(true);
won't work. You need to use:
CookieManager.getInstance().setAcceptThirdPartyCookies(true);
I ran into same issue and the above line worked as a charm.

Related

How can I stop a background video playing every time the user returns to the home page?

I have been handed a design which requires a background video to load when the users hits the home page. I realise that this isn't best practice, but the design has been signed off by the client, so trying to develop a decent solution for it. I have video in place and it is working nicely.
I have also been asked to ensure that the video only loads once when the user visits the site and when they navigate about the site, if they return to home, the video shouldn't play again.
I have been searching about the web, but can't find a precedent for this. Could anyone suggest a possible solution for this to work? Or some documentation that I could visit to source one?
The site is written with HTML, CSS and JQuery.
I appreciate that there isn't any code to see, but any suggestions would be much appreciated.
Thank you to anyone who stumbles across this.
Use localStorage or sessionStorage:
Supposing you have a video element with an id, e.g.:
<video id="myVideo">...</video>
Your script might look something like this:
if (!localStorage.getItem('alreadyPlayedVideo')) {
const myVideo = document.getElementById('myVideo');
myVideo.play();
localStorage.setItem('alreadyPlayedVideo', true);
}
It would look the same with sessionStorage. The primary difference between the two is that sessionStorage is cleared when the user exits the browser or closes the tab, whereas localStorage persists between sessions.
You have to check if the user was already on the site, so you have to save this data somewhere, data can be saved in session, database, localStorage or in cookies.
Using cookies would be the best option for this scenario. Cookies gets stored on client side and can be used for session and state management
Cookie usage with JS
function setCookie(cookieName, cookieValue, expireDays,isGlobal) {
var expireDate = new Date();
expireDate.setTime(d.getTime() + (expireDays*24*60*60*1000));
var expires = "expires="+expireDate.toUTCString();
if(isGlobal){
document.cookie = cookieName + "=" + cookieValue + "; " + expires+"; path=/";
}else{
document.cookie = cookieName + "=" + cookieValue + "; " + expires;
}
}
function getCookie(cookieName) {
var name = cookieName + "=";
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(cookieName) {
if (getCookie(cookieName) != "") {
return true;
} else {
return false;
}
}
$(document).ready(function(){
if(checkCookie('visited')){
//Stop playing video
}else{
setCookie('visited',1,3,false);
//Play video automatically
}
});

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 Cookie function only working on index file

I've created a function to show a cookie policy in my website. The cookie is stored across the website and is working fine but the show/hide part of it only works in the index file and not in all the other pages and I can't understand why.
The function is as follows:
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
(function() {
var InfoCookieCont = jQuery('#info_cookie');
var InfoCookieDiv = jQuery(".ok-cookie");
InfoCookieDiv.click(function() {
createCookie('infoCookie','true',365)
InfoCookieCont.removeClass("cookie-visible").addClass("cookie-hidden");
});
var InfoCookie = readCookie("infoCookie");
if (!InfoCookie) {
InfoCookieCont.removeClass("cookie-hidden").addClass("cookie-visible");
}
})();
This installs a cookie from my website and until you click the .ok-cookie button, the #info_cookie will keep showing up on top of the page thanks to the .cookie-visible class.
This works fine on index.php, but not in the other pages. In other pages it keeps the .cookie-hidden class even if I didn't click the ok-cookie button in the previous page.
The .js file where this function is, is of course included in every page of my website.
The live website is: www.valeriopierbattista.com
thanks for your help, im going crazy!
You've got some other js errors on the other pages which are killing the js script.

How to make JS page redirect trigger before page load

I am using the following script to redirect visitors of a page to another page on first visit, however it loads the index.html page first, and then triggers the redirect. Can anyone point me in the direction of how I might trigger this script before the page loads?
<script type="text/javascript">
function redirect(){
var thecookie = readCookie('doRedirect');
if(!thecookie){window.location = '/coming-soon.html';
}}
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','1');}
</script>
(the JS snippet used here was taken from Stack Overflow: JS to redirect to a splash page on first visit)
Thanks.
You don't need to wait while window is loaded:
<script type="text/javascript">
var thecookie = readCookie('doRedirect');
if(!thecookie) {
createCookie('doRedirect','true','1');
window.location = '/coming-soon.html';
};
function createCookie(name,value,days){
// do work
}
function readCookie(name){
// do work
}
</script>
Also Petr B. said right thing: server-side redirect is better in your case.
Try this How to Run a jQuery or JavaScript Before Page Start to Load.
Btw. if you want redirect without displaying page you must use php with cookies check.

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