Created
November 15, 2023 19:48
-
-
Save rockinghelvetica/5ba5619cfdcbac2afd73462a6301833b to your computer and use it in GitHub Desktop.
TwitterVideoURL
This file contains 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
document.addEventListener('DOMContentLoaded', (event) => { | |
const twitterVideoMenu = () => { | |
// The scripts are loaded, so you can run your code now | |
document.getElementById('react-root').addEventListener('click', async (event) => { | |
// This intercepts all clicks so let's make the test lightweight | |
if(!event.target.textContent.includes('Copy video address')) return false; | |
const getVariantsFromMemo = (domElement) => { | |
let variantsArray = []; | |
for (let key in domElement) { | |
if (key.startsWith('__reactProps') && domElement[key].children) { | |
for (let child of domElement[key].children) { | |
if (child && child._owner && child._owner.memoizedProps && child._owner.memoizedProps.variants) { | |
// Add flat | |
variantsArray.push(...child._owner.memoizedProps.variants); | |
} | |
} | |
} | |
} | |
return variantsArray.length > 0 ? variantsArray : null; | |
} | |
let videoComponent = event.target.closest('div[data-testid="videoComponent"]'); | |
console.log(videoComponent); | |
let variants = getVariantsFromMemo(videoComponent); | |
console.log(variants); | |
let highestBitrateVariant = variants.reduce((highest, variant) => { | |
if(variant.bitrate && (!highest || variant.bitrate > highest.bitrate)) { | |
return variant; | |
} else { | |
return highest; | |
} | |
}, null); | |
console.log(variants, highestBitrateVariant); | |
}, true); | |
} | |
// Content script injection | |
// Callback function to execute when mutations are observed | |
const callback = function(mutationsList, observer) { | |
for(let mutation of mutationsList) { | |
if (mutation.type === 'childList') { | |
// Check if the React root is now present | |
if (document.getElementById('react-root')) { | |
// If so, stop observing | |
observer.disconnect(); | |
// And run your code | |
twitterVideoMenu(); | |
} | |
} | |
} | |
}; | |
// Create an observer instance linked to the callback function | |
const observer = new MutationObserver(callback); | |
// Options for the observer (which mutations to observe) | |
const config = { attributes: true, childList: true, subtree: true }; | |
// Select the node that will be observed for mutations | |
const targetNode = document.body; // observe the whole body to capture the addition of 'react-root' | |
// Start observing the target node for configured mutations | |
observer.observe(targetNode, config); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment