Skip to main content

How to use cookies when 3rd party cookies is off in browsers

Updated at: Jan 11, 2021 Author: Yerassyl

Background: our plugins are considered as 3rd party on a websites they are installed. Safari blocks 3rd party cooies by default. Many browsers probably will do the same in the future. Many platforms (like jimdo) and sites are also requiring that we get cookie permission.

Problem: Some of our plugins might not work without cookies. Ex: popup, it depended on powrmodal#{id} to check if popup was shown before or not. Obviously when 3rd party cookie is blocked, we can't set/get this cookie. Therefore popup would appear every single time (ignoring Popup display options)

Hack solution: Even if plugin code is in 3rd party context to website, we have powr.js script that we install on users sites and it will have 1st party context, therefore it will have access to cookies.

How to get cookies?​

There is a helper method getImportantCookies, from there we return array of important cookies for particular appNamespace. NOTE: return only important cookies you need, and their requirements are clear to you. Do not just put whole list of know cookies just in case. Let's not confuse others.

// app/javascript/helpers/cookies/important_cookies.js
export const getImportantCookies = appModel => {
if (window.cookieEnabled()) return;
const { id, app_namespace: appNamespace } = appModel.meta;

if (appNamespace === 'popup') {
return [`powr_modal_${id}`, `powr_modal_${id}_submitted_at`];
}
if (appNamespace === 'formBuilder') {
return [`powr_form_${id}`];
}

// Add another if statemnt for your appNamespace
return [];
};

There is another version of getCookie that you will need to use for this hack to work:

// app/javascript/modules/helpers.js
window.getCookieWithBackupFromPowrjs = function(cName, useLocalStorageBackup) {
let cookie = window.getCookie(cName, useLocalStorageBackup);
if (!cookie && window.COOKIES && window.COOKIES.length > 0) {
cookie = window.COOKIES.find(cookie => cookie.cname === cName);
if (cookie) {
return cookie.value;
}
}
return cookie;
};

window.COOKIES array is defined in loadView.js

Then in notifyParentViewLoaded() method in loadView.js we send viewLoaded event to powr.js There we append list of cookies we want to get from powr.js:

r.data['cookiesToGet'] = getImportantCookies(window.APP_MODEL);

powr.js recieves event via settingsMessageReceived(evt) method, grabs needed cookies and returns them back with cookiesSent event.

loadView.js receives cookiesSent event in windowMessageReceived(evt) method, grabs cookies into window.COOKIES and re-renders app view via APP_VIEW.render();

Then in your code window.getCookieWithBackupFromPowrjs can access this cookies.

How to SET cookies?​

window.setCookie() method is already patched for that, it will send setCookie event to powr.js with your cookie if normal cookie set failed (because of 3rd party block).