1+ import { pollForElement } from "../sources/utils/poll-for-element" ;
2+ import { retailIdentifier } from "../types" ;
3+ /**
4+ * Dynamically parses a retail ID on the site url by polling for specific elements present on the checkout page.
5+ * @param {retailIdentifier } retail - The retail identifier object containing the elements to poll.
6+ * Please use a specific element id on a page to ascertain that the page should have a retail ID.
7+ * ! If not used correctly, we could append a retail ID to every page.
8+ * @example
9+ * const ecommerce = {
10+ * id: [
11+ * {
12+ * retailId: "California",
13+ * element: [".ca-element", "#california-element", "[data-state='CA-element']"],
14+ * fn: () => { console.log("Retail ID applied for California"); }
15+ * },
16+ * {
17+ * retailId: "New York",
18+ * element: [".ny-element", "#ny-element", "[data-state='NY-element']"],
19+ * fn: () => { console.log("Retail ID applied for New York"); }
20+ * },
21+ * ],
22+ * };
23+ * createRetailId(ecommerce);
24+ */
25+ export const createRetailId = ( retail : retailIdentifier ) => {
26+ const { id } = retail ;
27+
28+ const parseRetailId = ( ) => {
29+ id . forEach ( ( retail ) => {
30+ pollForElement ( retail . element , ( ) => {
31+ if ( ! retail . element ) return ;
32+ const baseUrl = window . location . href ;
33+ const url = new URL ( baseUrl ) ;
34+ const urlId = retail . retailId . replace ( / \s + / g, "" ) . toLowerCase ( ) ;
35+ retail . element . forEach ( ( elementSelector ) => {
36+ const element = document . querySelector ( elementSelector ) ;
37+ if ( element ) {
38+ console . log ( `Element detected for retail ID "${ retail . retailId } ": ${ elementSelector } ` ) ;
39+ }
40+ } ) ;
41+
42+ url . searchParams . set ( "retailId" , urlId ) ;
43+ window . history . replaceState ( { } , "" , url . toString ( ) ) ;
44+
45+ if ( retail . fn ) {
46+ retail . fn ( ) ;
47+ }
48+ } ) ;
49+ } ) ;
50+ } ;
51+
52+ parseRetailId ( ) ;
53+
54+ const checkUrlChange = ( ) => {
55+ window . navigation . addEventListener ( "navigate" , ( ) => {
56+ let previousUrl = sessionStorage . getItem ( "previousUrl" ) ;
57+ const currentUrl = window . location . href ;
58+ sessionStorage . setItem ( "currentUrl" , currentUrl ) ;
59+
60+ if ( currentUrl !== previousUrl ) {
61+ sessionStorage . setItem ( "previousUrl" , currentUrl ) ;
62+ parseRetailId ( ) ;
63+ }
64+ } ) ;
65+ } ;
66+
67+ setInterval ( checkUrlChange , 1000 ) ;
68+ } ;
0 commit comments