Skip to content

Instantly share code, notes, and snippets.

@iwoodruff
Last active April 18, 2024 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwoodruff/7744574bd96a26526bfb30327d3934ad to your computer and use it in GitHub Desktop.
Save iwoodruff/7744574bd96a26526bfb30327d3934ad to your computer and use it in GitHub Desktop.
Future Proof Replacement for Hardcoded `name="app-iframe"` Getter
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