Home > Software engineering >  Creating a cookie before redirecting to a page in JS
Creating a cookie before redirecting to a page in JS

Time:01-22

I have a problem with my script. I'm trying to force a script to create a cookie right after clicking on a linked element in an iframe, just before being redirected to the page that the iframe click leads to.

The click detection is done with the following code:

function iframeClick() {

if( getCookie('iframeclick') == false ) {       
    
    if(document.activeElement == document.querySelector("iframe")) {    
    setCookie('iframeclick', 'clicked', 1); 
    window.focus();
    }
} else { clearInterval(focused); }

}

var focused = window.setInterval(iframeClick, 300);

This method works best in Chrome, but in Opera and Firefox, sometimes the redirect is faster, so the cookie is not created.

Is there a way to delay the redirection or some other way to make the cookie creation always faster?

Detecting a click in the iframe using document.activeElement and creating a cookie before redirecting to the target page

CodePudding user response:

I am using this if I want to setCookies before redirecting in jquery. I hope it would help.

$(window).on('unload', function() {
   if (condition) {
      setCookie('iframeclick', 'clicked', 1); 
   }
}

CodePudding user response:

Maybe the simple solution for your situation is to wrap the code in a timeout, so you can be sure that it is executed after some period?

setTimeout(() => {
    setCookie('iframeclick', 'clicked', 1); 
}, 2000);
  • Related