Skip to content

Commit

Permalink
Fix YT subtitle detection
Browse files Browse the repository at this point in the history
  • Loading branch information
killergerbah committed Aug 8, 2024
1 parent be9f649 commit f12065c
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions extension/src/pages/youtube-page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { VideoData } from '@project/common';

declare global {
interface Window {
trustedTypes?: any;
}
}

let trustedPolicy: any = undefined;

if (window.trustedTypes !== undefined) {
trustedPolicy = window.trustedTypes.createPolicy('passThrough', {
createHTML: (s: string) => s,
createScript: (s: string) => s,
});
}

document.addEventListener(
'asbplayer-get-synced-data',
async () => {
Expand All @@ -15,15 +30,27 @@ document.addEventListener(
}
return webResponse.text();
})
.then((pageString) => new window.DOMParser().parseFromString(pageString, 'text/html'))
.then((pageString) => {
if (trustedPolicy !== undefined) {
pageString = trustedPolicy.createHTML(pageString);
}

return new window.DOMParser().parseFromString(pageString, 'text/html');
})
.then((page) => {
const scriptElements = page.body.querySelectorAll('script');

for (let i = 0; i < scriptElements.length; ++i) {
const elm = scriptElements[i];

if (elm.textContent?.includes('ytInitialPlayerResponse')) {
const context = new Function(`${elm.textContent}; return ytInitialPlayerResponse;`)();
let scriptString = `${elm.textContent}; return ytInitialPlayerResponse;`;

if (trustedPolicy !== undefined) {
scriptString = trustedPolicy.createScript(scriptString);
}

const context = new Function(scriptString)();

if (context) {
return context;
Expand Down

0 comments on commit f12065c

Please sign in to comment.