Get browser cookies - javascript

I'm trying to get the browser cookies using:
browser.cookies.getAll() but I always get this error in the console log instead:
Uncaught ReferenceError: browser is not defined
here's my code:
var gettingAll = browser.cookies.getAll({
url: "url"
});
console.log(gettingAll);

to get the url value u can use this solution :
var cookiesMap = document.cookie.split(";").map( value => {
var val =value.split("=")
var obj = { "key" : val[0], "value" : val[1] }
return obj;
});
for( var i = 0 ; i < cookiesMap.length ; i++ ){
if( cookiesMap[i].key==="url"){
console.log(cookiesMap[i].value);
}
}
hope it helps :)

Have a look at the following...
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
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 "";
}
Edit: fixed code block.

browser is indeed undefined. It's not a native JavaScript object.
You should use document.cookie (see here) instead.

Related

Cookie keeps defaulting to HttpOnly when not set to do so?

I am trying to add simple themes to my website. The script is supposed to create a theme cookie to see what theme is used and then apply the style. It used to work but now it gets set to httpOnly(meaning it cant be changed by JS even if it gets created by JS). It gets set to http only true even if I specifficaly try to set it to false which prevents me from changing it. Here is the code:
// Themes
var numOfThemes = 2;
var theme = 0;
// Standart getCookie function copied from w3schools
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 "";
}
// This function sets the theme depending on the value inside the theme cookie (eg.: "theme=3")
function applyTheme() {
var cookie = parseInt(getCookie("theme"));
var hs = document.getElementsByTagName('style');
if(hs.length > 1);
for (var i=0, max=hs.length; i < max; i++) {
hs[i].parentNode.removeChild(hs[i]);
}
switch(cookie) {
case 0:
theme = 0;
break;
case 1:
theme = 1;
var style = document.createElement('style');
style.innerHTML = ``;
document.head.appendChild(style);
break;
//...
}
}
// This is supposed to set the cookie inside the browser. I tried adding HttpOnly=false; at the end but it doesn't change anything
function setTheme(theme) {
const d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = "theme=" + theme + ";" + expires + ";path=/;SameSite=Lax;";
}
// this is the function for switching the theme on a button click
function themeSwitch() {
var theme = + parseInt(getCookie("theme")) + 1;
if(theme > 4) {
theme = 0;
}
setTheme(theme);
}
applyTheme();

How to pass values from one page to another by onclick in javascript?

1Page.js
function TableRow() {
let cells = document.querySelectorAll('#recieve-info td');
cells.forEach(cell => cell.onclick = function () {
let prevcell = cell.previousElementSibling;
if (prevcell) {
let LSItems;
let AddValue = '/images/back_arrow.png.png'
if (localStorage.getItem('passvalue') === null) {
LSItems = [];
} else {
LSItems = JSON.parse(localStorage.getItem('passvalue'));
}
LSItems.push([AddValue]);
localStorage.setItem('passvalue', JSON.stringify(LSItems));
let prev = prevcell.innerHTML;
console.log(prev);
}
});
}
I am trying to pass values by onclick, like if i click on the first one which is 'Save1' i want to save my value only in the first one.
2Page.js
function ParaG() {
document.querySelector('.Second-Para').innerHTML = JSON.parse(localStorage.getItem('passvalue'));
}
Here i want the values.
You can use cookies.
You can save the cookie:
document.cookie = "option=Option1";
And get the cookie:
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 "";
}
console.log(getCookie("option"))
https://w3schools.com/js/js_cookies.asp

Cookie returns NaN with parseInt

When I am trying to get the Cookie "Gold" which is a currency for my game, it returns NaN. right now the cookie is named "gold" and has a value of 7238 (for me obviously as I saved that as a cookie on my comp)
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 "";
}
var gold;
function getGold() {
if(getCookie("gold") == null) {
gold = 0;
} else {
var sup = getCookie("gold");
var co = parseInt(sup, 10);
gold += co;
}
}
getGold();
This results is NaN which is not helping as it isn't saying where I went wrong, I can also give the function I use to save cookies which is as followed:
function saveCookies(cname, value) {
var d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 *1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + value + ";" + expires + ";path=/";
}
Then when some hooligan clicks the "Save" button one of the functions it performs is
saveCookies("gold", gold")
That concludes all the information I could possibly give unless you need the whole program, which can be located at matrix-hub.com/CodeCoins.php
This results is NaN which is not helping as it isn't saying where I went wrong
First of all change this line saveCookies("gold", gold") to saveCookies("gold",7238) here your first argument is cookie name that is gold and second one is cookie value that should be 7238 not "gold"
Secondly, when you set var gold; the value of gold is undefined. So in your code block when you go to the else block because getCookie("gold") == null condition is false, value of gold is still undefined
var gold;
function getGold() {
if(getCookie("gold") == null) {
gold = 0;
} else {
var sup = getCookie("gold");
var co = parseInt(sup, 10); //7238
// this is where you messed up, undefined = undefined + 7238
gold += co;
}
return gold; // also missed this return line
}
console.log(getGold()); // it is returning NaN
Actually with this line gold += co; what do you want to accomplish ?
if you set cookie value gold=7238 then this line gold += co; should return 14476?

get regex pattern for current URL

I have a url like this:
http://mysite.aspx/results.aspx?s=bcs_locations&k="Hospital" OR "Office" OR...
The terms after k= are coming from checkboxes, when checked the checkboxes values are being passed. Now I need to get the current URL and get all the values after k, so if there are two 'Hospital' and Office then grab those values and make the checkboxes with those values checked.. Trying hard to persist the checked checkboxes coz on refresh, all the checked checkboxes loose their state..
Hospitals<input name="LocType" type="checkbox" value="Hospital"/>  
Offices<input name="LocType" type="checkbox" value="Office"/>  
Emergency Centers<input name="LocType" type="checkbox" value="Emergency"/>
What I have so far is:
I want the regular expression for such URl pattern..can someone help?
var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop("checked", true);
}
This is what we use to grab info from the query string. It's from another S.O. answer that I can't find. But this will give you an object which represents all the options in the query string.
var qs = function(){
var query_string = {};
if(window.location.search){
(function () {
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q)){
query_string[d(e[1])] = d(e[2]);
}
}());
}
return query_string;
};
You could do it like this:
var MyApp = {
urlArgs:{}
};
MyApp.processUrlArgs = function() {
this.urlArgs = {};
var str = window.location.search ? window.location.search.substring(1) : false;
if( ! str ) return;
var sp = str.split(/&+/);
var rx = /^([^=]+)(=(.+))?/;
var k, v, i, m;
for( i in sp ) {
m = rx.exec( sp[i] );
if( ! m ) continue;
this.urlArgs[decodeURIComponent(m[1])] = decodeURIComponent(m[3]);
}
};
But what I don't understand is why do it like this? If you work in asp why don't you use HttpUtility.ParseQueryString?
try this
function getParamsFromUrl(url){
var paramsStr = url.split('?')[1],
params = paramsStr.split('&'),
paramsObj = {};
for(var i=0;i < params.length; i++){
var param= params[i].split('='),
name = param[0],
value = param[1];
paramsObj[name] = value;
}
return paramsObj;
}
var testUrl = 'http://mysite.aspx/results.aspx?s=bcs_locations&k=Hospital';
getParamsFromUrl(testUrl);//return: Object { s="bcs_locations", k="Hospital"}

Javascript Cookies get by regex name

Hi how can i get cookies by regex names assuming that i have this cookies in browser cache
name: value:
text1 something
test something
text2 something
4 bla
like get cookies regex ('test'+onlynumbers)
returns
text1 something
text2 something
Something like this should work (untested):
var getCookieByMatch = function(regex) {
var cs=document.cookie.split(/;\s*/), ret=[], i;
for (i=0; i<cs.length; i++) {
if (cs[i].match(regex)) {
ret.push(cs[i]);
}
}
return ret;
};
getCookieByMatch(/^text\d+=/); // => ["text1=x;...", "text2=y..."]
Well, this is a way but not an elegant one I guess:
// demo cookie data
document.cookie="text2=mu";
document.cookie="text1=mu2";
document.cookie="otherText=mu3";
// helper function from
// http://codecandies.de/2010/02/15/js-library-namespace-und-erste-funktionen/
function getCookie(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;
}
// the function in question
function getCookieArray(regexp) {
cookieString = document.cookie;
filterResult = cookieString.match(regexp);
returnArr = {};
for(var i=0; i < filterResult.length; i++) {
returnArr[filterResult[i]]=getCookie(filterResult[i]);
}
return returnArr;
}
//demo run
function run() {
filteredCookies = getCookieArray(/text[0-9]+/g);
for(var key in filteredCookies)
alert(key+":"+filteredCookies[key]);
}
run();
Note that you need to add a "g" at the end of the regexp to get all cookies matching and not just the first one.

Categories

Resources