Last active
April 18, 2024 20:26
-
-
Save iwoodruff/7744574bd96a26526bfb30327d3934ad to your computer and use it in GitHub Desktop.
Future Proof Replacement for Hardcoded `name="app-iframe"` Getter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const API_KEY = '' // your app's apiKey, provided to your app during config, also accessible via window.shopify.config.apiKey | |
interface FrameList extends Window { | |
[index: number]: Window; | |
} | |
function findAppFrameSafely(frameName: string) { | |
if (window.parent) { | |
const frames = window.parent.frames as FrameList; | |
for (let i = 0; i < frames.length; i++) { | |
const frame = frames[i]; | |
try { | |
// referencing the name prop of a cross-origin frame will throw when there are multiple frames with the same name | |
if (frame.name === frameName) { | |
return frame; | |
} | |
} catch (_) { | |
// noOp | |
} | |
} | |
} | |
} | |
const legacyFrameName_doNotUse = 'app-iframe'; | |
const futureProofFrameName = `frame:${API_KEY}/main`; | |
const appFrame = findAppFrameSafely(legacyFrameName_doNotUse) || findAppFrameSafely(futureProofFrameName); | |
// continue doing whatever you were doing with the app's main frame | |
appFrame?.postMessage({}, window.location.origin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment