Enables cross-origin Web Workers (#35483)
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import initialState from '@/mastodon/initial_state';
|
||||
import { loadWorker } from '@/mastodon/utils/workers';
|
||||
|
||||
import { toSupportedLocale } from './locale';
|
||||
|
||||
@@ -9,9 +10,8 @@ let worker: Worker | null = null;
|
||||
export async function initializeEmoji() {
|
||||
if (!worker && 'Worker' in window) {
|
||||
try {
|
||||
worker = new Worker(new URL('./worker', import.meta.url), {
|
||||
worker = loadWorker(new URL('./worker', import.meta.url), {
|
||||
type: 'module',
|
||||
credentials: 'omit',
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Error creating web worker:', err);
|
||||
|
||||
@@ -36,15 +36,16 @@ async function fetchAndCheckEtag<ResultType extends object[]>(
|
||||
): Promise<ResultType | null> {
|
||||
const locale = toSupportedLocaleOrCustom(localeOrCustom);
|
||||
|
||||
let uri: string;
|
||||
// Use location.origin as this script may be loaded from a CDN domain.
|
||||
const url = new URL(location.origin);
|
||||
if (locale === 'custom') {
|
||||
uri = '/api/v1/custom_emojis';
|
||||
url.pathname = '/api/v1/custom_emojis';
|
||||
} else {
|
||||
uri = `/packs${isDevelopment() ? '-dev' : ''}/emoji/${locale}.json`;
|
||||
url.pathname = `/packs${isDevelopment() ? '-dev' : ''}/emoji/${locale}.json`;
|
||||
}
|
||||
|
||||
const oldEtag = await loadLatestEtag(locale);
|
||||
const response = await fetch(uri, {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'If-None-Match': oldEtag ?? '', // Send the old ETag to check for modifications
|
||||
|
||||
29
app/javascript/mastodon/utils/workers.ts
Normal file
29
app/javascript/mastodon/utils/workers.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Loads Web Worker that is compatible with cross-origin scripts for CDNs.
|
||||
*
|
||||
* Returns null if the environment doesn't support web workers.
|
||||
*/
|
||||
export function loadWorker(url: string | URL, options: WorkerOptions = {}) {
|
||||
if (!('Worker' in window)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if the script origin and the window origin are the same.
|
||||
const scriptUrl = new URL(import.meta.url);
|
||||
if (location.origin === scriptUrl.origin) {
|
||||
// Not cross-origin, can just load normally.
|
||||
return new Worker(url, options);
|
||||
}
|
||||
} catch (err) {
|
||||
// In case the URL parsing fails.
|
||||
console.warn('Error instantiating Worker:', err);
|
||||
}
|
||||
|
||||
// Import the worker script from a same-origin Blob.
|
||||
const contents = `import ${JSON.stringify(url)};`;
|
||||
const blob = URL.createObjectURL(
|
||||
new Blob([contents], { type: 'text/javascript' }),
|
||||
);
|
||||
return new Worker(blob, options);
|
||||
}
|
||||
Reference in New Issue
Block a user