I created a dark and light mode in my laravel project and whenever the vue JS toggle is clicked it should create a cookie that saves the value. It works perfectly fine on google chrome but when i tried it on edge and firefox it showed (Undefined array key "isDarkModeOn").
I just want this cookie to be saved to any browser
My toggle Vue component which includes create cookie
<template>
<div
@click="store.modeToggle(), modeToggle()"
>
<div
:
>
<div
:
></div>
</div>
</div>
</template>
<script>
import { store } from "./store.js";
export default {
props: ["theme"],
data() {
return {
store,
};
},
mounted() {
if (this.theme === "false") {
store.light();
} else {
store.dark();
}
},
methods: {
dark() {
this.$emit("dark");
},
light() {
this.$emit("light");
},
modeToggle() {
if (
this.darkMode ||
document.querySelector("body").classList.contains("dark")
) {
this.light();
} else {
this.dark();
}
const isDarkModeOn = store.toggleActive;
createCookie("isDarkModeOn", isDarkModeOn.toString(), 60 * 60 * 24);
},
},
};
</script>
<style></style>
my Js file which contains the logic for creating the cookie
function createCookie(name, value, timeInSeconds) {
var date = new Date();
date.setTime(date.getTime() timeInSeconds * 1000);
var expires = "; expires=" date.toGMTString();
document.cookie = name "=" value expires "; path=/";
}
function getCookie(cname) {
let name = cname "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(";");
for (let i = 0; i < ca.length; i ) {
let c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
window.onload = function () {
const isDarkModeOn = getCookie("isDarkModeOn");
if (isDarkModeOn === "true") document.body.classList.add("dark");
};
and this is how I tell browser to display dark class or hide it according to the cookie if it exists
<body id="app" style="font-family: Open Sans, sans-serif" >
It works on chrome but not on any other browser.
Also when testing in Laravel like this
@if ($value = $_COOKIE['isDarkModeOn'])
{{ $value }}
@else
'not found'
@endif
It echos the value not problem so since there is a cookie why any other browser can't identify it
CodePudding user response:
As for your test, you should use something more safe (doesnt trigger an error when absent)
@if (isset($_COOKIE['isDarkModeOn']))
{{ $_COOKIE['isDarkModeOn'] }}
@else
'not found'
@endif
CodePudding user response:
Issue is solved by adding the below lines of code before the body
<?php
if (isset($_COOKIE['isDarkModeOn'])) {
$cookie = $_COOKIE['isDarkModeOn'];
} else {
$cookie = '';
}
?>
Not the best way to do it but It did the trick