Placing event listeners on individual cookies - javascript

I'm trying to create an extension from chrome which monitors a specified cookie and takes action when its value is overwritten. I'm aware that the cookies library has an onChanged() event listener but I don't know how to use for specific cookies.
For example, if I visit google.com, it stores a cookie called "NID"-- how do I make an event listener specifically for it?

From the documentation, it doesn't seem like you can monitor individual cookies. What you can do, however, is check the cookie after the callback is fired to determine whether to take action.
Since the callback is passed a changeInfo parameter containing information about the cookie and the reason for the change, you can just check that and fire another function if necessary.

Related

GTM - Do not fire an HTML tag if the customer refreshes the page

We have currently an order confirmation page on our website after the customer paid where information is sent to our analytics tools.
If the customer refreshes the page, the information about his order is sent again to our analytics tool and then we get wrong/duplicate information in our orders statistics.
Is there an easy way to prevent this?
The goal would be here to not trigger the custom html tag when the customer reloads the page.
It should be only fired once.
Thanks!
Best,
Victor
You can use PerformanceNavigation.type or PerformanceNavigationTiming.type respectively in a Javascript variable to find out if the page has been reloaded (the former is already marked as deprecated while the latter is still marked as experimental, so to be on the safe side you should probably check which one is supported by the browser and use that).
Then use the return value to detect reloads and block the tag depending on that.
An alternative would be to set a cookie or local storage entry with the transaction and block based on that.
We finally found another solution that seems to work: We used an additional trigger in GTM that prevent the info to be sent twice.
When calling the page for the first time, the condition is set to "false", and on each following request to that page it is set to "true".
We made some test orders and it seems to works correctly. Thanks!

how to add event listener to cookie so that to notify when a cookie gets updated or expired

I want to add an event listener to Cookie.
My objective is to call an function, once one of the cookies get expired.
I tried the following given in mozilla:-
browser.cookies.onChanged.addListener(listener)
browser.cookies.onChanged.removeListener(listener)
browser.cookies.onChanged.hasListener(listener)
but its not working in chrome browser.
I seacrhed google but could not get any help
Any help in this regard as how to add event listener to cookie
Right now, there is no API for watching the cookies.
This browser.cookies.onChanged that you refer to is only for browser extension https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/onChanged.
You can use the following npm package https://www.npmjs.com/package/#fcannizzaro/react-use-cookie-watcher.
If you check the implementation, it just adds a setInterval which reads cookies and waits for changes https://github.com/fcannizzaro/react-use-cookie-watcher/blob/9281ec0a5b6fbcbafd4589f0ea32d2b59bec32b3/src/index.tsx#L31.
So you can do it on your own if you want 😉

How to perform an ajax call on page unload?

I have a dashboard where users can toggle some input values in order to configure the appearance of the page.
I want to store those changes in a DB table, so when user comes back, the dashboard appears according to the specific user configuration retrieved from the DB.
I know how to send those values to DB and how to retrieve them
I don't want to make ajax calls every time the user changes a configuration.
Instead, I think this senario would be better:
Page load (retrieve DB configuration if exist)
User toggles the configuration ui items (e.g. checkboxes, select etc) and the appropriate client side changes take place (some divs get hidden, some others are shown etc and the config input values are stored to a hidden field), but no ajax call takes place.
When user clicks a link to another page, the configuration input values (which have been stored to the hidden field) are sent to the DB via ajax call.
MY QUESTION
One solution(?) would be the use of onbeforeunload event like this:
window.onbeforeunload = function(e) {
// Perform the ajax call
return 'Do you want to save the configuration changes?';
};
But, if the user's browser prevent popups, the function will not get executed?
Is there a way to perform an ajax call on onbeforeunload event, without calling a dialog box?
No. During unload, the browser will kill all pending requests. So the AJAX might or might not arrive at the server. You also can't do it inside the handler of the beforeunload event because the first A in AJAX means: Asynchronous -> Just put the request on the stack and eventually execute it. So the request will be looked at only after the handler returns. But very soon after that, the browser will kill anything related to the page.
The solution is to always send updates to the server while the users makes changes. Put those into a special "temporary" table from which you can restore the state later.
You could also use something like localStorage in the browser but then, the data wouldn't move with the user. For example if they were working on an tablet and that broke or had a power loss, they could move to their PC to continue where they left off.
You can't guarantee that an Ajax call will complete in this way, see Aaron's response. My suggestion would be to use something like localStorage to read / write the user's settings instead.
If you need a user's appearance to persist across multiple devices, add a periodic request to read / write the recent updates from localStorage to the central DB.
Try using Navigator.sendBeacon on the visibilitychange event.
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
navigator.sendBeacon("/ajaxUrl");
}
});
Regarding Navigator.sendBeacon(), MDN details that when leaving a page,
the browser may choose not to send asynchronous XMLHttpRequest requests.
With the sendBeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. This means:
The data is sent reliably
Regarding the visibilitychange event, MDN recommends:
Web sites often want to send analytics or diagnostics to the server when the user has finished with the page. The most reliable way to do this is to send the data on the visibilitychange event

Get Transition qualifier in chrome.webRequest.onBeforeSendHeaders

I want to find if the url is being accessed is entered by the user or if its something that's being loaded in the background due to other reasons. This information is available through the transaction qualifier that's available in chrome.webNavigation.onCommitted. I want to add this as an additional header information in chrome.webRequest.onBeforeSendHeaders.
However, onCommitted is fired after onBeforeSendHeaders.
Is there any other way to get this information before OnBeforeSendHeaders is fired? I tried chrome.tabs.getCurrent in webNavigation.OnBeforeNavigate, but the callback doesn't have any info in the returned tab object (its undefined).
Any help will be appreciated.

Google Analytics - multiple domain tracking

Could anyone clarify how the GA actions _gaq.push(['_link', <href>]); and _gaq.push(['_linkByPost', <form>]); work?
I'm not interested on how to use them as presented in the documentation. I understand those scenarios. I want to know more about what they do when called.
Edit:
I suspect how this works but I need some confirmation from someone that fiddled with this longer than me. I want to know what the process is in each of the cases in small steps. I know that it changes the sent data in order to overwrite to cookie on the target site, but I need to know exactly the actions that happen (in terms of JavaScript on the sending page) after you do the push.
I would also like to know if I could use _gaq.push(['_link', <href>]); from anywhere in my code to change the page.
Thank you,
Alin
We will assume _gaq.push(['_setAllowLinker', true]); used on any needed page.
What _gaq.push(['_link', <href>]); does:
Appends the __utm<x> cookies to <href>. You need to return false in the onclick of the anchor so that the original link does not follow through.
Changes the browser location to the newly formed URL.
What _gaq.push(['_linkByPost', <form>]); does:
Changes the action attribute of <form> so that it includes the __utm<x> cookies.
What happens on the target page:
The GA script on the target page checks the received parameters and if the __utm<x>s are sent it overwrites its own cookies with these. This results in identifying the user as being the same on that left your original page.
As a bonus _gaq.push(['_link', <href>]); can be used in (almost) any situation window.open(<href>); can be used.
They pass the cookie information from one domain to another; in the instance, it does this by appending a query string on the next page; with _linkByPost, it sends the cookie information as GET parameters on the form action along with your POST data.
If _setAllowLinker is set to true on the target page, the cookie information sent will overwrite the default Google Analytics cookies on the target page, and will allow for linked, consistent session information between the two, as the cookies will ensure that consistent data is shared.
EDIT:
No, you can't call it from anywhere in your page, unless you bind it to an onclick of where you'd like it called.

Categories

Resources