How to import a custom Javascript tag in an extension-only app

According to the documentation, the object document is not present in the app, so the traditional way of document.head.appendChild(customScript); does not work.

importScripts does not seem to work as well. I get the error:
Uncaught (in promise) NetworkError: Failed to execute ‘importScripts’ on ‘WorkerGlobalScope’: The script at ‘<script_location>‘ failed to load.

Is there another way of doing it? Or is it simply not possible?

I can import a custom JS tag if I simply add them in Settings > Customer Events. However, I cannot do it via an app. Is this really the case?

Hello!

App Pixel extension runs in a Web Worker, so there’s no DOM, hence no document to push script tags to.

importScripts is the supported solution in this case. If it fails in your case, it’s probably caused by something else, e.g. CORS issues, etc.

Hope this helps.

I checked and my script has the Access-Control-Allow-Origin: * response header. As a test, I tried using importScripts with the jquery script and it returns the same error:

importScripts(`https://code.jquery.com/jquery-3.7.1.min.js`);

I imagine the jquery script does not have any CORS issues and that it should work.

Do you happen to have any functioning JS or any example so I could test it?

All app pixel scripts are loaded using importScripts, inside the Web Worker sandbox.

As an example, here’s what the initial Web Worker script looks like for an app pixel.

// https://example.com/web-pixels@ae1676cfwd2530674p4253c800m34e853cb/web-pixel-227737656@e57a43765e0d230c1bcb12178c1ff13f/sandbox/worker.modern.js

// Internal sandbox runtime
importScripts('https://example.com/cdn/wpm/sae1676cfwd2530674p4253c800m34e853cbm.js');
globalThis.shopify = self.webPixelsManager.createShopifyExtend('227737656', 'APP');

// Third party code published through the CLI (app pixel)
importScripts('/web-pixels/strict/app/web-pixel-227737656@e57a43765e0d230c1bcb12178c1ff13f.js');

Then, inside that last script, the app pixel, importScripts can be used again. E.g. TikTok’s pixel loads its own Shopify-specific integration script "https://analytics.tiktok.com/i18n/pixel/shopify.js"

I believe that importScripts may throw the same error as a failure to load if the script content can’t be run inside a Web Worker. jQuery is not meant for Web Workers, so that’s probably why it fails.

don’t mean to be rude but if you “need” to import jQuery in app pixels you should stop right now, turn off the PC then throw it out the window.

1 Like

As I have clearly said in my message, I just tried to import jquery to discard possible CORS issues that emileber had mentioned, as it is a widely used script and shouldn’t have any CORS problems. I never said that i “needed” to import it and had no intention whatsoever to use it.

Shopify’s extension-only app pixels are a bit limited for our case right now so we won’t be using it for the moment.