Skip to content

Instantly share code, notes, and snippets.

@ncaq
Last active August 7, 2023 00:52
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 ncaq/0ba3d4524bdb6263ee64e08602127d86 to your computer and use it in GitHub Desktop.
Save ncaq/0ba3d4524bdb6263ee64e08602127d86 to your computer and use it in GitHub Desktop.
Twitterの埋め込みスクリプトをボタンを押さずに取得します。
/**
* Twitterの埋め込みスクリプトをボタンを押さずに取得します。
*/
async function getTwitterEmbed(url) {
// TwitterのURLやツイートのURLじゃない場合は`undefined`を返します。
if (
!(
(url.hostname === "twitter.com" || url.hostname === "mobile.twitter.com") &&
/^\/\w+\/status\/\d+/.exec(url.pathname)
)
) {
return undefined;
}
const publish = new URL("https://publish.twitter.com/oembed");
publish.searchParams.set("url", url.href);
// `script`タグは最後にまとめて入れるので取り除きます。
publish.searchParams.set("omit_script", "t");
// ブラウザの言語設定を反映します。
publish.searchParams.set("lang", navigator.language || "en");
const response = await fetch(publish.href);
if (!response.ok) {
throw new Error(`${publish.href}: response is not ok ${JSON.stringify(response.statusText)}`);
}
return (await response.json()).html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment