1let requestCount = {}; 2let nonceValue = ''; 3let currentPage = ''; 4let versionValue = false; 5 6self.addEventListener( 'message', function ( event ) { 7 if ( event.data === 'newspack-reset-request-count' ) { 8 requestCount = {}; 9 } 10 if ( event.data.indexOf( 'newspack-nonce-' ) === 0 ) { 11 nonceValue = event.data.replace( 'newspack-nonce-', '' ); 12 } 13 if ( event.data.indexOf( 'newspack-version-' ) === 0 ) { 14 versionValue = event.data.replace( 'newspack-version-', '' ); 15 } 16} ); 17 18const findProperty = payload => { 19 const found = payload.match( /tid=([\w-]*)/ ); 20 if ( found ) { 21 return found[ 1 ]; 22 } 23}; 24 25const sendMessage = message => 26 fetch( 27 `/wp-json/newspack-manager/v1/sw-message?message=${ encodeURIComponent( 28 `${ message } (URL: ${ currentPage })` 29 ) }&nonce=${ nonceValue }&version=${ versionValue }` 30 ); 31 32const handlePageViewForProperty = ( clientId, property ) => { 33 if ( ! requestCount[ clientId ] ) { 34 requestCount[ clientId ] = {}; 35 } 36 requestCount[ clientId ][ property ] = requestCount[ clientId ][ property ] + 1 || 1; 37 if ( requestCount[ clientId ][ property ] > 1 ) { 38 sendMessage( `Property \`${ property }\` has sent more than two pageviews per request.` ); 39 } 40}; 41 42self.addEventListener( 'fetch', async event => { 43 const url = event.request.url; 44 if ( url.match( /google-analytics\.com.*\/collect/ ) ) { 45 if ( ! event.clientId ) { 46 return; 47 } 48 const client = await self.clients.get( event.clientId ); 49 if ( ! client ) { 50 return; 51 } 52 currentPage = client.url; 53 const { search } = new URL( url ); 54 let property = findProperty( search ); 55 let params = search.replace( /^\?/, '' ).split( '&' ); 56 const text = await event.request.text(); 57 if ( ! property ) { 58 property = findProperty( text ); 59 } 60 if ( property ) { 61 params = params.concat( text.split( '&' ) ); 62 if ( 63 // GA4 64 params.includes( 'en=page_view' ) || 65 // UA 66 params.includes( 't=pageview' ) 67 ) { 68 handlePageViewForProperty( event.clientId, property ); 69 } 70 } 71 } 72} );
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.