Closed
Description
Hi, developers
When I host a multi-threaded package on platforms like jsDelivr with proper cross-origin isolation settings, I encounter an error such as:
Uncaught SecurityError: Failed to construct 'Worker': Script at 'https://cdn.jsdelivr.net/npm/xxx' cannot be accessed from origin 'http://127.0.0.1:8080'.
This issue arises because workers cannot be created across different origins. According to the discussion in this Webpack issue and the solution proposed in this comment, we can use fetch to bypass this limitation.
A potential solution is modify the allocateUnusedWorker
function from
allocateUnusedWorker() {
var worker;
var workerOptions = {
"type": "module","name": "em-pthread"
};
worker = new Worker(new URL("your js file", import.meta.url), workerOptions);
PThread.unusedWorkers.push(worker);
}
to
allocateUnusedWorker() {
var workerOptions = {
type: "module",
name: "em-pthread"
};
try {
// Use XMLHttpRequest for a synchronous request
var xhr = new XMLHttpRequest();
xhr.open("GET", new URL('your js file', import.meta.url), false); // false means synchronous request
xhr.send(null);
// Check if the request was successful
if (xhr.status === 200) {
const scriptText = xhr.responseText; // Get the response text
// Create a Blob URL
const workerUrl = URL.createObjectURL(new Blob([scriptText], {
type: 'application/javascript'
}));
// Create a Worker and add it to the unused Workers list
PThread.unusedWorkers.push(new Worker(workerUrl, workerOptions));
} else {
console.error('Failed to fetch the script:', xhr.status);
}
} catch (error) {
console.error("Error occurred while allocating worker:", error);
}
}
Metadata
Metadata
Assignees
Labels
No labels