BuilderIO / partytown

Relocate resource intensive third-party scripts off of the main thread and into a web worker. 🎉
https://partytown.builder.io
MIT License
12.99k stars 431 forks source link

404 error for the resource "/partytown/partytown-sandbox-sw.html?1646853715625" #107

Closed naveedahmed1 closed 2 years ago

naveedahmed1 commented 2 years ago

I recently tried integrating Partytown for my website Mustakbil.com but encountered this error https://github.com/BuilderIO/partytown/issues/38#issuecomment-1060066828

Which thankfully, has been fixed in the latest version of Partytown (v 0.4.5), but now I am receiving 404 error for the resource "/partytown/partytown-sandbox-sw.html?1646853715625"

Below are the steps I followed to add partytown to my website:

I copied contents of @builder.io\partytown\lib\partytown.js and added it to the script tag in my index.html file.

  <script>
    !function (t, e, n, i, r, o, a, d, s, c, p, l) { function u() { l || (l = 1, "/" == (a = (o.lib || "/~partytown/") + (o.debug ? "debug/" : ""))[0] && (s = e.querySelectorAll('script[type="text/partytown"]'), i != t ? i.dispatchEvent(new CustomEvent("pt1", { detail: t })) : (d = setTimeout(w, 1e4), e.addEventListener("pt0", f), r ? h(1) : n.serviceWorker ? n.serviceWorker.register(a + (o.swPath || "partytown-sw.js"), { scope: a }).then((function (t) { t.active ? h() : t.installing && t.installing.addEventListener("statechange", (function (t) { "activated" == t.target.state && h() })) }), console.error) : w()))) } function h(t) { c = e.createElement(t ? "script" : "iframe"), t || (c.setAttribute("style", "display:block;width:0;height:0;border:0;visibility:hidden"), c.setAttribute("aria-hidden", !0)), c.src = a + "partytown-" + (t ? "atomics.js?v=0.4.5" : "sandbox-sw.html?" + Date.now()), e.body.appendChild(c) } function w(t, n) { for (f(), t = 0; t < s.length; t++)(n = e.createElement("script")).innerHTML = s[t].innerHTML, e.head.appendChild(n); c && c.parentNode.removeChild(c) } function f() { clearTimeout(d) } o = t.partytown || {}, i == t && (o.forward || []).map((function (e) { p = t, e.split(".").map((function (e, n, i) { p = p[i[n]] = n + 1 < i.length ? "push" == i[n + 1] ? [] : p[i[n]] || {} : function () { (t._ptf = t._ptf || []).push(i, arguments) } })) })), "complete" == e.readyState ? u() : (t.addEventListener("DOMContentLoaded", u), t.addEventListener("load", u)) }(window, document, navigator, top, window.crossOriginIsolated);
  </script>

Added below config just above the Partytown script:

  <script>
    window.partytown = {
      forward: ["dataLayer.push", "fbq"],
      lib: "/partytown/",
      resolveUrl: function (url) {
        if (url.hostname === 'www.google-analytics.com') {
          var proxyUrl = new URL('https://myproxyurl.com/');
          proxyUrl.searchParams.append('url', url.href);
          return proxyUrl;
        }
        return url;
      }

    };
  </script>

Below is my Google Tag Manager code:

<script type="text/partytown">
    (function (w, d, s, l, i) {
        w[l] = w[l] || []; w[l].push({
          'gtm.start':
            new Date().getTime(), event: 'gtm.js'
        }); var f = d.getElementsByTagName(s)[0],
          j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
            'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
      })(window, document, 'script', 'dataLayer', 'GTM-NJFTK74');
  </script>

Tag Manager code adds:

adamdbradley commented 2 years ago

If you are receiving a 404 for that file then it means the service worker is not correctly intercepting the requests. Also, make sure all of the files are copied to your directory, not just partytown.js: https://partytown.builder.io/copy-library-files

naveedahmed1 commented 2 years ago

Thanks @adamdbradley.

I have uploaded all contents of @builder.io/partytown/lib as mentioned here https://partytown.builder.io/copy-library-files

I have also confirmed there isn't any file with name partytown-sandbox-sw.html in node_modules\@builder.io\partytown\lib directory.

hiepxanh commented 2 years ago

@naveedahmed1 if you dont mind, can you make a small tutorial for the document section for angular ? :D

naveedahmed1 commented 2 years ago

@hiepxanh sure, I'd love to :)

For now I just followed the HTML guide under Integrations section (https://partytown.builder.io/html) but I have yet to make it work :D

garciadiazjaime commented 2 years ago

I'm experiencing same issue,

it seems sandbox-sw.html is required when window.crossOriginIsolated = false, which instead of using Atomics fallbacks to use service-worker.

sandbox-sw.html doesn't seem to be find in partytown repo although is referred in the snippet.ts file.

hope you find something 😸

naveedahmed1 commented 2 years ago

Thanks @garciadiazjaime while this is fixed, I would also be interested in using Atomics but this requires below headers to be set:

Cross-Origin-Embedder-Policy: credentialless
Cross-Origin-Opener-Policy: same-origin

Ref: https://partytown.builder.io/atomics#document-response-headers

but I was wondering if setting these headers have any impact on third party scripts like Adsense?

garciadiazjaime commented 2 years ago

hey @naveedahmed1 it seems Adsense "doesn't like" SharedArrayBuffer

Is there a way to use Google Adsense with cross origin isolation?

however it seems you can register for a token: https://developers.google.com/publisher-tag/guides/cross-origin-embedder-policy

I'm still intrigued about how sandbox-sw.html is supposed to be generated, I can't seem to find a clue in the repo, in my case I would like to make partytown to work with service-workers,

hope you get better luck and share the findings 😄

naveedahmed1 commented 2 years ago

I updated the Partytown inline code and updated sandbox-sw.html to sandbox-sw.js but even that doesn't work.

adamdbradley commented 2 years ago

The partytown-sandbox-sw.html file is not provided in the distribution because it's a handled response from the service worker. I've added a note to the distribution docs about this: https://partytown.builder.io/distribution#builderiopartytownlib

naveedahmed1 commented 2 years ago

Thanks @adamdbradley

I am now receiving below error:

Uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
    at VM5477 partytown-sandbox-sw.html:2:5448
    at Array.map (<anonymous>)
    at D (VM5477 partytown-sandbox-sw.html:2:5398)
    at VM5477 partytown-sandbox-sw.html:2:6842
    at Worker.J.onmessage (VM5477 partytown-sandbox-sw.html:2:25834)

Below is my code:

  <script type="text/javascript">
    //partytown config
    window.partytown = {
      forward: ["dataLayer.push", "fbq"],
      lib: "/partytown/",
      resolveUrl: function (url) {
        if (url.hostname === 'www.google-analytics.com') {
          var proxyUrl = new URL('https://myproxyurl/');
          proxyUrl.searchParams.append('url', url.href);
          return proxyUrl;
        }
        return url;
      }

    };

    //inline partytown script
/* Partytown 0.4.5 - MIT builder.io */
!function(t,e,n,i,r,o,a,d,s,c,p,l){function u(){l||(l=1,"/"==(a=(o.lib||"/~partytown/")+(o.debug?"debug/":""))[0]&&(s=e.querySelectorAll('script[type="text/partytown"]'),i!=t?i.dispatchEvent(new CustomEvent("pt1",{detail:t})):(d=setTimeout(w,1e4),e.addEventListener("pt0",f),r?h(1):n.serviceWorker?n.serviceWorker.register(a+(o.swPath||"partytown-sw.js"),{scope:a}).then((function(t){t.active?h():t.installing&&t.installing.addEventListener("statechange",(function(t){"activated"==t.target.state&&h()}))}),console.error):w())))}function h(t){c=e.createElement(t?"script":"iframe"),t||(c.setAttribute("style","display:block;width:0;height:0;border:0;visibility:hidden"),c.setAttribute("aria-hidden",!0)),c.src=a+"partytown-"+(t?"atomics.js?v=0.4.5":"sandbox-sw.html?"+Date.now()),e.body.appendChild(c)}function w(t,n){for(f(),t=0;t<s.length;t++)(n=e.createElement("script")).innerHTML=s[t].innerHTML,e.head.appendChild(n);c&&c.parentNode.removeChild(c)}function f(){clearTimeout(d)}o=t.partytown||{},i==t&&(o.forward||[]).map((function(e){p=t,e.split(".").map((function(e,n,i){p=p[i[n]]=n+1<i.length?"push"==i[n+1]?[]:p[i[n]]||{}:function(){(t._ptf=t._ptf||[]).push(i,arguments)}}))})),"complete"==e.readyState?u():(t.addEventListener("DOMContentLoaded",u),t.addEventListener("load",u))}(window,document,navigator,top,window.crossOriginIsolated);
  </script>

  <script type="text/partytown" src="https://www.googletagmanager.com/gtm.js?id=GTM-NJFTK74"></script>
  <script type="text/partytown">
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      'gtm.start':
        new Date().getTime(), event: 'gtm.js'
    });
  </script>

Can you please guide if I am still missing something?

naveedahmed1 commented 2 years ago

Probably its looking for requestContent

TypeError: Cannot read properties of undefined (reading 'requestContent')

sandeshpe commented 2 years ago

Using atomics maybe a bad idea, since mobile browsers doesn't support atomics. https://caniuse.com/mdn-javascript_builtins_atomics

sandeshpe commented 2 years ago

@naveedahmed1 @garciadiazjaime I tried integrating GTM with partytown but seems like similar issues. My doubleclick script is failing. Apparently it is not able to parse the content of the script downloaded from doubleclick.

image
hiepxanh commented 2 years ago

I have 404 error for the resource "/partytown/partytown-sandbox-sw.html" error too, @naveedahmed1 how do you solve this problem? I really cannot understand that html file not exist but still request to server. 😢

dezman commented 1 year ago

Side note: enabling Atomics breaks stripe payment, which seems to require 'Cross-Origin-Embedder-Policy', 'unsafe-none'

terza98 commented 1 year ago

Side note: enabling Atomics breaks stripe payment, which seems to require 'Cross-Origin-Embedder-Policy', 'unsafe-none'

Were you able to fix this issue? Stripe form breaks for me as well when I use 'Cross-Origin-Embedder-Policy': 'credentialess'

simkuns commented 1 year ago

I have 404 error for the resource "/partytown/partytown-sandbox-sw.html" error too, @naveedahmed1 how do you solve this problem? I really cannot understand that html file not exist but still request to server. 😢

I was following HTML integration tutorial, however, I was getting the same error. After visiting https://partytown.builder.io/tests/benchmarks/ I was able to copy the .html file (https://partytown.builder.io/~partytown/debug/partytown-sandbox-sw.html?1675291925139=) from there and paste it into /~partytown/debug/ folder and partytown started working with { debug: true }.

partytown-sandbox-sw.html:

<!DOCTYPE html><html><head><meta charset="utf-8"><script src="./partytown-sandbox-sw.js?v=0.7.5-dev1674668837610"></script></head></html>
simkuns commented 1 year ago

Note: when { debug: false } CMD+Shift+R on Firefox 109 MacOS causes same 404 error, but normal refresh loads service worker correctly.

MaximeGratens commented 1 year ago

Any news about that ?

drjaydenm commented 1 year ago

Note: when { debug: false } CMD+Shift+R on Firefox 109 MacOS causes same 404 error, but normal refresh loads service worker correctly.

Also seeing this on Firefox 113 on Windows. I always do a Ctrl+Shift+R by habit to reload my site and was certain something was broken. Can confirm it doesn't do this on a normal refresh.

craigrileyuk commented 8 months ago

Same. Hard reload gets a 404, soft refresh works fine.

MTheProgrammer commented 8 months ago

Same here. Is it possible to configure meta robots of the page returned by worker? For example:

<meta name="robots" content="noindex">
netzpixel commented 3 months ago

I have the exact same problem and so far no solution... Any tips on how to solve this?