A space to discuss online store customization, theme development, and Liquid templating.
We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more
Hello.
I have code that in a Web Pixel service worker that sets a cookie from a URL parameter. It should then read that cookie on page_view and checkout_completed, and send it to my server.
It seems that I can set the cookie, but reading the cookie still returns undefined.
Can someone advise? See code below.
Note: It's also been a nightmare getting the Web Pixel code to update. I literally have to create a new development store each time. If anyone can assist in that area, I would be appreciative. Thanks!
import {register} from "@shopify/web-pixels-extension";
register(({ configuration, analytics, browser, init }) => {
const { window } = init.context;
const bcParams = new URLSearchParams(window.location.search);
let bcEntries = Object.fromEntries(bcParams.entries());
var bcAffiliateId = bcEntries.bc_aff_id;
console.log('2.11.1', bcAffiliateId);
browser.cookie.set('bc_id', bcAffiliateId);
analytics.subscribe('page_viewed', async(event) => {
const proposalId = await browser.cookie.get('bc_id');
console.log('from cookie', proposalId);
const jsonString = JSON.stringify({proposal_id: proposalId, action: 'view'});
console.log(jsonString);
if (proposalId) {
browser.sendBeacon('https://xxxxx/api/affiliate', jsonString);
}
});
analytics.subscribe('checkout_completed', async(event) => {
const orderId = event.data.checkout.order.id;
const proposalId = await browser.cookie.get('bc_id');
const jsonString = JSON.stringify({proposal_id: proposalId, order_id: orderId, action: 'order'});
if (proposalId) {
browser.sendBeacon('https://xxxxx/api/affiliate', jsonString);
}
});
});
Hi @daveluke
I think you want to set the cookie in one event and read in another.
Right now you are writing outside of any event scope. In general I believe it should also work like this - if all code is executed on all pages. But I do not know. We are successfully writing cookies (incl. expire, path and domain) in page_viewed and reading checkout_completed.
Hope this helps