Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name endchan.org tiktok
- // @namespace Violentmonkey Scripts
- // @match https://endchan.org/jp/res/1288.html*
- // @grant GM_xmlhttpRequest
- // @grant unsafeWindow
- // @grant GM_getResourceText
- // @require https://cdn.jsdelivr.net/npm/[email protected]/js/browser/bluebird.js
- // @resource css https://lf16-tiktok-web.tiktokcdn-us.com/obj/tiktok-web-tx/tiktok/falcon/embed/embed_lib_v1.0.13.css
- // @resource js https://lf16-tiktok-web.tiktokcdn-us.com/obj/tiktok-web-tx/tiktok/falcon/embed/embed_v1.0.13.js
- // @version 1.0
- // @author -
- // @description Undo broken tiktok embed code, and apply something that works.
- // ==/UserScript==
- function isValidVideo(url) {
- const match = url.match(new RegExp("/video/\\d+"))
- return match
- }
- function extractTiktokURL(el) {
- const a = el.querySelector("a")
- if (a) {
- return a.href
- } else {
- console.warn("invalid", el)
- return undefined
- }
- }
- async function httpRequest(opts) {
- return new Promise((resolve, reject) => {
- const defaults = {
- method: "GET",
- onload: (response) => resolve(response.responseText),
- onerror: (error) => reject(error)
- }
- const request = Object.assign({}, defaults, opts)
- GM_xmlhttpRequest(request)
- })
- }
- async function createTiktokEmbed(url) {
- const escaped = encodeURIComponent(url)
- const div = document.createElement("div")
- div.classList.add("tiktok")
- const oembed = await httpRequest({
- url: `https://www.tiktok.com/oembed?url=${escaped}`
- })
- const data = JSON.parse(oembed)
- div.innerHTML = data.html
- console.log(url, data.html)
- const div2 = document.createElement("div")
- const a = document.createElement("a")
- a.target = "_blank"
- a.href = url
- a.innerText = url
- div2.append(a)
- div.append(div2)
- return div
- }
- async function replaceTiktok(el) {
- const url = extractTiktokURL(el)
- const div = await createTiktokEmbed(url)
- el.replaceWith(div)
- }
- function replaceWithURL(el, url) {
- const a = document.createElement("a")
- a.href = url
- a.innerText = url
- el.replaceWith(a)
- }
- async function main() {
- // Add CSS
- const css = GM_getResourceText("css")
- let style = document.createElement("style");
- style.type = "text/css";
- style.appendChild(document.createTextNode(css));
- document.head.appendChild(style);
- // Find tiktok videos and replace markup.
- const tts = document.querySelectorAll("span.tiktok_wrapper")
- const res = await Promise.map(tts, async (tt) => {
- const url = extractTiktokURL(tt)
- if (isValidVideo(url)) {
- await replaceTiktok(tt)
- } else {
- console.warn("invalid", url)
- //replaceWithURL(tt, url)
- }
- },
- {
- concurrency: 1
- })
- // Apply tiktok embed special sauce.
- with (unsafeWindow) {
- const js = GM_getResourceText("js")
- const script = document.createElement("script")
- script.appendChild(document.createTextNode(js))
- //document.body.append(script)
- }
- }
- main()
Advertisement