Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(extension): capture dynamically loaded Instagram posts

tianma-if03141020d67b
diff --git a/apps/extension/instagram-clip.test.mjs b/apps/extension/instagram-clip.test.mjs
new file mode 100644
index 00000000..2996ab7b
--- /dev/null
+++ b/apps/extension/instagram-clip.test.mjs
@@ -0,0 +1,62 @@
+import { expect, test } from 'bun:test';
+import { createDocument, createWindow } from '@mixmark-io/domino';
+import { runInNewContext } from 'node:vm';
+import { bundleTestScripts } from './bundle-test-scripts.mjs';
+import { readMetaSocial, metaPostCard } from './src/social-clip.ts';
+import { platformTarget } from './src/platform-clip.ts';
+
+const url = 'https://www.instagram.com/p/SelectedPost/';
+const source = 'https://www.instagram.com/';
+const media = { code: 'SelectedPost', user: { username: 'author' }, caption: { text: 'A full caption beyond the preview' }, taken_at: 1700000000,
+ media_type: 8, carousel_media_count: 3, carousel_media: [1,2,3].map(i => ({ media_type: 1, image_versions2: { candidates: [{url:`https://images.example.test/${i}.jpg`,width:1000,height:1000}] } })) };
+const json = value => `<script type="application/json">${JSON.stringify(value)}</script>`;
+const feed = `<article><a href="/author/">author</a><a href="/p/SelectedPost/"><time datetime="2026-10-08T08:40:23Z">2 weeks</time></a><img src="https://images.example.test/1.jpg"><p>A full caption... <button>more</button></p><button>Like</button><button>Share</button></article>`;
+const [bundle] = bundleTestScripts(['capture-platform']);
+
+async function capture({ html=feed, data=media, status=200, change, contentType='text/html', responseUrl=url, sourceUrl=source }={}) {
+ const w=createWindow(html,sourceUrl), location={href:sourceUrl};
+ Object.getPrototypeOf(w.document.querySelectorAll('*'))[Symbol.iterator] ??= Array.prototype[Symbol.iterator];
+ const calls=[];
+ let done;
+ const result = new Promise(resolve=>{done=resolve;});
+ runInNewContext(bundle, { window:w,document:w.document,location,URL,AbortSignal,setTimeout,clearTimeout,setInterval,clearInterval,
+ DOMParser:class {parseFromString(html){return createDocument(html);}},
+ __edgeeverPlatformClipPayload:{requestId:'instagram',url,sourceUrl},
+ fetch:async (request,init)=>{calls.push({url:request,init});change?.(w.document,location);return {ok:status===200,url:responseUrl,headers:new Headers({'content-type':contentType}),text:async()=>json(data)};},
+ chrome:{i18n:{getMessage:k=>k},runtime:{sendMessage:async message=>done(message.result)}},
+ });
+ return {result:await result,calls};
+}
+
+test('Instagram dynamic feed fetches only the selected same-origin detail and keeps all carousel images',async()=>{
+ const {result,calls}=await capture();
+ expect(result.ok).toBe(true);expect(result.clip.url).toBe(url);expect(result.clip.author).toBe('author');
+ expect(result.clip.markdown).toContain(media.caption.text);expect(result.clip.markdown.match(/!\[/g)).toHaveLength(3);
+ expect(calls).toHaveLength(1);expect(calls[0].url).toBe(url);
+ expect(calls[0].init.credentials).toBe('same-origin');expect(calls[0].init.redirect).toBe('error');
+});
+
+for (const failure of ['wrong-post','login','redirect','http','not-html','incomplete','navigation','recycled','hidden','no-card']) test(`Instagram detail fallback rejects ${failure}`,async()=>{
+ const {result,calls}=await capture({
+ data:failure==='wrong-post'?{...media,code:'OtherPost'}:failure==='login'?{login:true}:failure==='incomplete'?{...media,carousel_media:media.carousel_media.slice(0,1)}:media,
+ status:failure==='http'?403:200,contentType:failure==='not-html'?'application/json':'text/html',
+ responseUrl:failure==='redirect'?'https://www.instagram.com/accounts/login/':url,
+ html:failure==='hidden'?feed.replace('<article>','<article hidden>'):failure==='no-card'?'<main>Log in</main>':feed,
+ change:(doc,location)=>{if(failure==='navigation')location.href='https://www.instagram.com/p/OtherPost/';if(failure==='recycled')doc.querySelector('a[href="/p/SelectedPost/"]').setAttribute('href','/p/OtherPost/');},
+ });
+ expect(result.ok).toBe(false);expect(result.clip).toBeUndefined();
+ expect(calls).toHaveLength(['hidden','no-card'].includes(failure)?0:1);
+});
+
+test('Instagram fallback preserves the current host, including the non-www origin',async()=>{
+ const {result,calls}=await capture({sourceUrl:'https://instagram.com/',responseUrl:'https://instagram.com/p/SelectedPost/'});
+ expect(result.ok).toBe(true);expect(calls[0].url).toBe('https://instagram.com/p/SelectedPost/');
+});
+
+test('Instagram detail card includes media and caption rather than the likes footer or comments',()=>{
+ const doc=createDocument(`<main><div id="post"><img src="https://images.example.test/1.jpg"><div><a href="/author/">author</a><p>${media.caption.text}</p></div><div id="footer"><a href="/liker/"><img src="https://images.example.test/avatar.jpg">liker</a><button>Like</button><button>Share</button><button>Save</button><a href="/author/p/SelectedPost/"><time datetime="2026-10-08T08:40:23Z">October 8</time></a></div></div><div>COMMENT SENTINEL</div></main>${json(media)}`);
+ expect(metaPostCard(doc.querySelector('time').parentElement,'instagram',url).id).toBe('post');
+ const result=readMetaSocial(doc,platformTarget(url));
+ expect(result.ok).toBe(true);expect(result.clip.markdown).toContain(media.caption.text);
+ expect(result.clip.markdown).not.toContain('COMMENT SENTINEL');
+});
diff --git a/apps/extension/package.json b/apps/extension/package.json
index 462390c8..736751da 100644
--- a/apps/extension/package.json
+++ b/apps/extension/package.json
@@ -9,7 +9,7 @@
"dev": "vite --config vite.config.ts",
"lint:firefox": "web-ext lint --source-dir dist-firefox --output text",
"package:firefox": "bun run build:firefox && bun run lint:firefox && web-ext build --source-dir dist-firefox --artifacts-dir web-ext-artifacts --overwrite-dest",
- "test": "bun test manifest.test.mjs context-menus.test.mjs popup.test.mjs capture-bundle.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs zhihu-clip.test.mjs reddit-clip.test.mjs video-clip.test.mjs page-images.test.mjs notebook-clip.test.mjs clip-time.test.mjs platform-clip.test.mjs social-clip.test.mjs platform-capture.test.mjs platform-save.test.mjs vertical-clip.test.mjs article-clip.test.mjs"
+ "test": "bun test manifest.test.mjs context-menus.test.mjs popup.test.mjs capture-bundle.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs zhihu-clip.test.mjs reddit-clip.test.mjs video-clip.test.mjs page-images.test.mjs notebook-clip.test.mjs clip-time.test.mjs platform-clip.test.mjs social-clip.test.mjs instagram-clip.test.mjs platform-capture.test.mjs platform-save.test.mjs vertical-clip.test.mjs article-clip.test.mjs"
},
"dependencies": {
"@mixmark-io/domino": "2.2.0",
diff --git a/apps/extension/src/capture-platform.ts b/apps/extension/src/capture-platform.ts
index 7e5c1d97..43c199ae 100644
--- a/apps/extension/src/capture-platform.ts
+++ b/apps/extension/src/capture-platform.ts
@@ -6,6 +6,7 @@ import { readXiaoyuzhou } from "./xiaoyuzhou-clip";
import { readBoss } from "./boss-clip";
import { readXueqiu } from "./xueqiu-clip";
import { readXueqiuFeedPost } from "./xueqiu-feed";
+import { readInstagramDetail } from "./instagram-clip";
import { readArticle } from "./article-clip";
import { readJike, jikeExpandButton, jikePostCard } from "./jike-clip";
import { readDouban } from "./douban-clip";
@@ -68,6 +69,9 @@ import { platformHtmlMarkdown, platformTarget, type PlatformLabels, type Platfor
}
if(expected.platform === "xueqiu" && !platformTarget(location.href)) return readXueqiuFeedPost(document,expected,sourceUrl);
const initial = read();
+ if (expected.platform === "instagram" && !initial.ok && (initial.reason === "unreadable" || initial.reason === "incomplete")) {
+ return readInstagramDetail(document, expected, sourceUrl, samePage);
+ }
if (!initial.ok && initial.reason === "incomplete" && ["facebook", "linkedin", "jike"].includes(expected.platform)) {
const card = expected.platform === "jike" ? jikePostCard(document,expected,location.href) : socialPostCard(document,expected);
const expand = expected.platform === "jike" ? jikeExpandButton(document,card) : expected.platform === "facebook" ? facebookExpandButton(card) : linkedinExpandButton(card);
diff --git a/apps/extension/src/instagram-clip.ts b/apps/extension/src/instagram-clip.ts
new file mode 100644
index 00000000..dc4ec0b1
--- /dev/null
+++ b/apps/extension/src/instagram-clip.ts
@@ -0,0 +1,34 @@
+import { instagramPostCard, readMetaSocial } from "./social-clip";
+import { platformTarget, type PlatformRead, type PlatformTarget } from "./platform-clip";
+
+/** Feed items loaded after navigation are absent from the document's JSON.
+ * Read only the selected post's same-origin HTML, without executing its scripts. */
+export const readInstagramDetail = async (
+ doc: Document, target: PlatformTarget, sourceUrl: string, samePage: () => boolean,
+): Promise<PlatformRead> => {
+ const source = new URL(sourceUrl);
+ if (target.platform !== "instagram" || source.protocol !== "https:"
+ || !["www.instagram.com", "instagram.com"].includes(source.hostname)) return { ok: false, reason: "not-target" };
+ const card = instagramPostCard(doc, target);
+ if (!card) return { ok: false, reason: "unreadable" };
+ const current = () => samePage() && doc.contains(card) && instagramPostCard(doc, target) === card;
+ try {
+ const url = new URL(`/p/${target.id}/`, source);
+ const response = await fetch(url.href, {
+ credentials: "same-origin", redirect: "error", headers: { Accept: "text/html" },
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!current()) return { ok: false, reason: "changed" };
+ if (!response.ok || !response.headers.get("content-type")?.includes("text/html")
+ || Number(response.headers.get("content-length")) > 10_000_000) return { ok: false, reason: "unreadable" };
+ if (response.url && (new URL(response.url).origin !== source.origin
+ || platformTarget(response.url)?.url !== target.url)) return { ok: false, reason: "changed" };
+ const html = await response.text();
+ if (!current()) return { ok: false, reason: "changed" };
+ if (html.length > 10_000_000) return { ok: false, reason: "unreadable" };
+ const detail = new DOMParser().parseFromString(html, "text/html");
+ return readMetaSocial(doc, target, detail);
+ } catch {
+ return { ok: false, reason: current() ? "unreadable" : "changed" };
+ }
+};
diff --git a/apps/extension/src/social-clip.ts b/apps/extension/src/social-clip.ts
index bb73899e..908508e3 100644
--- a/apps/extension/src/social-clip.ts
+++ b/apps/extension/src/social-clip.ts
@@ -235,6 +235,12 @@ export const readBluesky = (doc: Document, target: PlatformTarget): PlatformRead
return saved;
};
+const instagramCardHasMedia = (card: Element, base: string) => Array.from(card.querySelectorAll('img[src], video')).some(media => {
+ if (platformElementHidden(media)) return false;
+ const link = media.closest('a[href]');
+ return !link || platformTarget(postLinkUrl(link, base))?.platform === "instagram";
+});
+
/** Bound Meta posts by their timestamp header and rendered action controls. */
export const metaPostCard = (link: Element, platform: string, base: string): Element | null => {
if (!link.querySelector("time[datetime]") || link.closest("[hidden], [aria-hidden='true'], script, style, template")) return null;
@@ -257,7 +263,10 @@ export const metaPostCard = (link: Element, platform: string, base: string): Ele
return socialPlatform(url.href) === platform && (platform === "threads" ? /^\/@[^/]+\/?$/.test(url.pathname) : /^\/[^/]+\/?$/.test(url.pathname));
} catch { return false; }
});
- if (card.matches('article, [role="article"]') || (profile && card.querySelectorAll('button, [role="button"]').length >= 3)) return card;
+ // Instagram's detail timestamp lives in the action footer. Keep walking
+ // until the card also contains the media, rather than returning that footer.
+ if (card.matches('article, [role="article"]') || (profile && card.querySelectorAll('button, [role="button"]').length >= 3
+ && (platform !== "instagram" || instagramCardHasMedia(card, base)))) return card;
}
return null;
};
@@ -313,8 +322,18 @@ const mediaImages = (item: RecordValue, base: string): string[] | null => {
}
return images.filter(Boolean);
};
-export const readMetaSocial = (doc: Document, target: PlatformTarget): PlatformRead => {
- const media = metaMedia(doc, target);
+export const instagramPostCard = (doc: Document, target: PlatformTarget): Element | null => {
+ if (target.platform !== "instagram") return null;
+ for (const link of ownPostLinks(doc.documentElement, "instagram")) {
+ if (!sameTarget(postLinkUrl(link, target.url), target)) continue;
+ const card = metaPostCard(link, "instagram", target.url);
+ if (card && !platformElementHidden(card) && instagramCardHasMedia(card, target.url)) return card;
+ }
+ return null;
+};
+
+export const readMetaSocial = (doc: Document, target: PlatformTarget, detail?: Document): PlatformRead => {
+ const media = metaMedia(detail || doc, target);
if (!media) return { ok: false, reason: "unreadable" };
const username = text(record(media.user)?.username);
if (target.platform === "threads" && username && username.toLowerCase() !== target.id.split("/")[0]) return { ok:false, reason:"changed" };
@@ -324,7 +343,9 @@ export const readMetaSocial = (doc: Document, target: PlatformTarget): PlatformR
if (target.platform === "instagram" && Array.isArray(media.carousel_media)) {
captions.push(...media.carousel_media.map((slide) => text(record(record(slide)?.caption)?.text)));
}
- if (!readableMetaCard(doc,target,captions)) return {ok:false,reason:"unreadable"};
+ // A fetched, identity-matched detail supplies the full caption for a visible
+ // feed preview. Do not require that preview to contain the untruncated text.
+ if (detail ? !instagramPostCard(doc, target) : !readableMetaCard(doc,target,captions)) return {ok:false,reason:"unreadable"};
const slides = Array.from(new Set(captions.slice(1).filter(Boolean)));
const combined = slides.join("\n\n");
const normalized = (value: string) => value.replace(/\s+/g,"");