Can only have one function in JS module - javascript

I found this post on how to write a cookie with Blazor (as it turns out, that involves JavaScript). Using the sample from the post, I made my own version, with both a Write and a Read function. So it looks like this:
<script>
window.blazorExtensions = {
WriteCookie: function (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
};
ReadCookie: function (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 "";
}
}
</script>
Only problem is... It doesn't work :-(
If I only have theWriteCookie method it works. If I only have the ReadCookie method it works. But if I have both, it does not work.
From the looks of it, the window part is a module, but I could be wrong. However, this it what VS Code says, in the tool tip:
Can anyone explain to me, why this does not work? I tried Google, but since I struggle with the terminology, it's hard to find something useful. I am used to C# and thought that the window.blazorExtension was some sort of namespace.
If it's any help, here is how I invoke the functions:
public async Task WriteCookeAsync() {
var test = await JSRuntime.InvokeAsync<object>("blazorExtensions.WriteCookie", "Color", colorCode, 7);
}

Without actually checking your functions' for correctness, I can see the object window.blazorExtensions is not defined correctly. What you need to do is to change the semi-colon after the WriteCookie function definition to a comma as JavaScript object properties are comma-separated...
window.blazorExtensions = {
WriteCookie: function (name, value, days) {
//...
},
ReadCookie: function (cname) {
//...
},
};

Related

How to create page visit counting like PHP session on JavaScript (client) side

Is it possible to create a session number of page view/visit like PHP, but in JavaScript?
$_SESSION['views'] = 0;
Is it possible to keep track of the number even when user quite the page and get back again?
You could use Cookies. On visit get the cookie and increment it by 1. Or set it to 1 if it doesn't exist
Example:
<p id="yolo"> </p>
<script>
var numberOfVisits = function getCookie('numberOfVisits');
if (numberOfVisits == "")
{
setcookie('numberOfVisits', 1, 100);
}
else
{
numberOfVisits++;
setcookie('numberOfVisits', numberOfVisits, 100);
}
document.getElementById('yolo').innerHTML = getCookie('numberOfVisits');
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 "";
}
function setcookie(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=/";added
}
</script>
If you only need the data on the client side then use
window.localStorage, it stores data with no expiration date on the client side and it does not send it to the server on every request like cookies, as explained here.
<script>
var varname = "VISIT_COUNTER";
if (localStorage.getItem(varname) === null) {
localStorage.setItem(varname, 1);
} else {
var visits_count = parseInt(localStorage.getItem(varname)) + 1;
localStorage.setItem(varname, visits_count);
console.log("Total visits: " + visits_count);
}
</script>

Run javascript function once a week

I have the below javascript function that currently runs on every visit. I do not want to spam our visitors with this popup on every visit so I am trying to get my head around cookies and running this once a week.
setTimeout(function() {
jQuery(document).one('mouseleave', function() {
console.log('mouse left');
jQuery('.open-popup-link').magnificPopup('open');
});
}, 10000);
I placed this within a cookie function that I found on here however nothing runs and no errors in the console.
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 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) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var pinball = getCookie("pinball");
if (pinball === "") { // Cookie not set
setTimeout(function() {
jQuery(document).one('mouseleave', function() {
console.log('mouse left');
jQuery('.open-popup-link').magnificPopup('open');
});
}, 10000);
setCookie("pinball", "seen", 7);
}
}
What have I missed or need to do to make this run?
I agree with #MysterX about local storage, but to answer your question - from reading your code - there does not seem to be a call to trigger checkCookie() which means that there are no errors because the function has not run.
You should probably have:
$(document).ready(function(){
checkCookie()
})
also you have a typo in the first section of code and in the checkCookie function as well - same error - you have :
jQuery(document).one('mouseleave', function() {...
and it should be .
jQuery(document).on('mouseleave', function() {...
Using localStorage, only call checkSeen once per page load, or execute it inside of setInterval for browsers that never close.
function popup() {
...
}
function updateSeen() {
var sec = Math.round(Date.now()/1000);
localStorage.setItem("seen", sec);
return sec;
}
function checkSeen() {
var seen = localStorage.getItem("seen") || updateSeen();
var now = Math.round(Date.now()/1000);
var week = 604800;
if ((now - seen) >= week) {
updateSeen();
popup();
}
}
checkSeen();

Javascript Cookie function

I have an question relating to my cookie function. Does it really have to have the $(function) for the if(readCookie) or can I specify just function like the rest of the code above it?
I've tried setting it a few different ways but without the $function it doesn't read the set cookie.
Can anybody help put me in the right direction. Thank you.
<script>
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();
}`enter code here`
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(){
if(readCookie("style") == 'Dark'){
$("body").removeClass().addClass("colour-scheme-1");
$(".styleswitch a").removeClass().addClass("Dark");
}
else {
}
});
</script>
Yes, that's required. What that's doing is deferring execution of the code in that function until after the DOM has been completely built. If you didn't have that, then depending on exactly where on the page that script is imported it might not work at all.
If you were to move the whole <script> block to the very end of the <body>, it'd work without the jQuery "ready" setup.

Cookie to show a popup every 30 days

<script type="text/javascript">
jQuery(document).ready(function(){
if (document.cookie.indexOf('visited=false') == -1)
{
var fifteenDays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});
</script>
What's wrong with my above code my facebook like popup is called every time the page is loaded in my blog. I just to show only one time every 30 days.How i can do that?
Your particular implementation looks like it has you checking the cookie for 'visited=false', but setting the cookie to 'visited=true' so your if statement will never match.
I'd suggest you use a proven set of cookie manipulation functions and then your task will be pretty easy.
Here are the cookie functions I use when my environment doesn't already have them:
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);
}
Once you have those, you can do this:
jQuery(document).ready(function() {
var visited = readCookie('visited');
if (!visited || visited !== "true") {
createCookie('visited', "true", 30);
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});

Any way that I can assign window.open(url) into cookies array in javascript?

Does anyone know how can I assign window.open(url) into cookies array in javascript?
Below is the code that I used at the moment, but seem not really working well for me....
var expiredays = 30
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie="childWindowHandles["+num+"] =" +window.open(url)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
document.cookie === String
window.open === Object
Object !== String
therefore
document.cookie !== window.open
It would be better to assign the uri string into the cookie array of the window you want to open then pull it out of the cookie when you want to call window.open. Inserting code or sensitive data into a cookie isn't good practice or secure.
Functions taken from: http://www.quirksmode.org/js/cookies.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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Then you could go:
createCookie('openUri', uriToOpen);
var openUri = readCookie('openUri');
if (openUri) {
window.open(openUri, 'myWindow');
}
Or something like that.
Hope this helps.

Categories