Last active
August 7, 2023 00:52
-
-
Save ncaq/0ba3d4524bdb6263ee64e08602127d86 to your computer and use it in GitHub Desktop.
Twitterの埋め込みスクリプトをボタンを押さずに取得します。
This file contains hidden or 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
/** | |
* 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