|
1 |
| -import nullthrows from 'nullthrows'; |
2 |
| - |
3 |
| -function injectCode(code: string) { |
4 |
| - const script = document.createElement('script'); |
5 |
| - script.textContent = code; |
6 |
| - |
7 |
| - nullthrows(document.documentElement).appendChild(script); |
8 |
| -} |
9 |
| - |
10 |
| -// Listen for the message posted by the window from the code we are injecting |
11 |
| -// below into the current page |
12 |
| -window.addEventListener('message', function(evt) { |
13 |
| - if (evt.source !== window || !evt.data) { |
14 |
| - return; |
15 |
| - } |
16 |
| - if (typeof evt.data.hasDetectedShopify !== 'undefined') { |
17 |
| - chrome.runtime.sendMessage({ |
18 |
| - type: 'detect-shopify', |
19 |
| - hasDetectedShopify: evt.data.hasDetectedShopify, |
20 |
| - }); |
21 |
| - } |
| 1 | +// Use regex on document to test for a shopify site |
| 2 | +// Look for a DOM script element that contains |
| 3 | +// "Shopify.shop =" |
| 4 | +// This is auto-generated from content_for_header |
| 5 | +const findShopifyScript = Array.from( |
| 6 | + document.querySelectorAll('script'), |
| 7 | +).filter(script => { |
| 8 | + return /Shopify\.shop =/.test(script.textContent || ''); |
22 | 9 | });
|
23 | 10 |
|
24 |
| -// We need to inject this detect code into the current page because even though |
25 |
| -// this Content Script has access to the same DOM as the current page, it does |
26 |
| -// not share the same JS global scope. |
27 |
| -const detectShopify = ` |
28 |
| - window.postMessage({ |
29 |
| - hasDetectedShopify: typeof window.Shopify !== 'undefined', |
30 |
| - }, '*'); |
31 |
| -`; |
32 |
| - |
33 |
| -injectCode(detectShopify); |
| 11 | +if (findShopifyScript.length) { |
| 12 | + chrome.runtime.sendMessage({ |
| 13 | + type: 'detect-shopify', |
| 14 | + hasDetectedShopify: true, |
| 15 | + }); |
| 16 | +} |
0 commit comments