Skip to content

'Web workers' do not work in editor #3414

Closed
@quarks

Description

@quarks

p5.js version

1.11.1

What is your operating system?

Mac OS

Web browser and version

Firefox 136.0.2 (64bit) & Safar 18.3.1i

Actual Behavior

Although it is possible to create a web worker object, posting and receiving messages from it does not appear to work.

I have created a simple sketch in the editor to demonstrate the problem.

Expected Behavior

The sketch should display a randomly display a rectangle every 2 seconds, it uses a web worker to calculate the position and size and send the information back to the main sketch. This works as expected using VSC but fails in the web editor.

Steps to reproduce

Steps:

I have included the code below but it is easier to see it in action in the editor here.

Snippet:

main.js

let worker, n = 1, x = 0, y = 0, w = 0, h = 0;

function setup() {
    p5canvas = createCanvas(320, 240);
    worker = new Worker('worker.js');
    worker.onmessage = (e) => { processMessage(e.data) };
    worker.postMessage(`Rectangle ${n++}`);
    setInterval(() => { worker.postMessage(`Rectangle ${n++}`); }, 2000)
}

function processMessage(info) {
    [x, y, w, h] = [info.x, info.y, info.w, info.h];
}

function draw() {
    background(255, 240, 255);
    fill(255, 170, 100); stroke(0); strokeWeight(3);
    rect(x, y, w, h);
}

worker.js

onmessage = function (message) {
    let x = 50 + Math.floor(Math.random() * 100);
    let y = 20 + Math.floor(Math.random() * 100);
    let w = 100 + Math.floor(Math.random() * 100);
    let h = 50 + Math.floor(Math.random() * 50);
    postMessage({ action: 'done', x: x, y: y, w: w, h: h });
}

Activity

added
BugError or unexpected behaviors
on Mar 23, 2025
welcome

welcome commented on Mar 23, 2025

@welcome

Welcome! 👋 Thanks for opening your first issue here! And to ensure the community is able to respond to your issue, be sure to follow the issue template if you haven't already.

dipamsen

dipamsen commented on Mar 23, 2025

@dipamsen
Contributor

Seems to work on Chrome. Tried on Firefox, but failed with

Loading Worker from “https://preview.p5js.org/quark-js/sketches/7CjKpWsSy/worker.js” was blocked because of a disallowed MIME type (“text/html”).

So user files are being served with a default text/html mime type instead of identifying the mime type based on the file extension.

I can work on a fix for this.

Sanjai-Shaarugesh

Sanjai-Shaarugesh commented on Mar 23, 2025

@Sanjai-Shaarugesh

#3414

This is the correct code

// fixes in declaration in variable and it's dimensions 
let worker;
let n = 1;
let x = 50;
let y = 50;
let w = 100;
let h = 80;
function setup() {
    p5canvas = createCanvas(320, 240)
    worker = new Worker('worker.js');
    // console.log(worker)
    // Define method for receiving messages sent from worker
    worker.onmessage = (e) => {
        // fixes in simply log the message but don't update the rectangle to show extra info to the user 
        console.log("Message received:", e.data);
    };
    // Post message to worker
    worker.postMessage(`Rectangle ${n++}`);
    // Repeat the message every 2 seconds thereafter
    setInterval(() => { worker.postMessage(`Rectangle ${n++}`); }, 2000)
}
function draw() {
    background(255, 240, 255);
    fill(255, 170, 100); stroke(0); strokeWeight(3);
    rect(x, y, w, h);
}

I have made a few changes in this code

  • I have declared variables separately instead of declaring multiple variables at once
  • Set fixed values for x, y, w, h to keep the rectangle in a static position
  • Changed processMessage() to console.log() to bypass the updating of rectangle coordinates

These changes ensure the rectangle stays fixed at the specified position (50,50) with dimensions 100×80, while still allowing communication with the worker.

Sanjai-Shaarugesh

Sanjai-Shaarugesh commented on Mar 23, 2025

@Sanjai-Shaarugesh

#3414

Web workers work fine in all browsers

The problem was only in the code, and I have fixed the issues in the code. Bugs have been fixed too. 🪲

quarks

quarks commented on Mar 23, 2025

@quarks
Author

I think you misunderstood my problem. The code I posted worked fine in VSC on my desktop but not in the in the p5js web editor. @dipamsen discovered that the problem appears to be with the mime type and is browser specific. I tried the web editor in Chrome and confirmed that the sketch worked as expected.

So there was nothing wrong with my code and it was in fact correct. The changes you made were superficial and did not change the program logic.

dipamsen

dipamsen commented on Mar 24, 2025

@dipamsen
Contributor

I have added the fix in #3416, by which the sketch works properly in firefox:

Image

However, I have realised something else while working on this - This only works for a sketch which is saved to someone's account, and thus has a sketchId. If a non-logged in user tries to use this on the default sketch provided on the home page, it doesn't work, since it does not have any sort of url like https://preview.p5js.org/USERNAME/sketches/SKETCHID/worker.js to fetch the worker file from. (I believe this issue is beyond just web workers, it will affect anytime a file is 'fetch'ed from JavaScript)

I am unsure what the general solution for this issue is - somehow replace file path strings with Blob URLs? cc @raclim

quarks

quarks commented on Mar 25, 2025

@quarks
Author

That's great you have identified the problem created a fix and potentially uncovered a larger issue. Nice work!

ksen0

ksen0 commented on Mar 25, 2025

@ksen0
Member

Really cool investigation work, everyone! Jumping in to share a couple of resources here related to answering style @Sanjai-Shaarugesh: in the future, please be a little more mindful of answer tone. In this case, there is an issue worth discussing here, and it's always best to take the time to really understand the problem before jumping in with a fix. Additionally, please consult the PF guidelines on answering questions on Discourse which is also good to have in mind in GitHub spaces!

raclim

raclim commented on Mar 25, 2025

@raclim
Collaborator

Thanks for raising and looking into this issue!

However, I have realised something else while working on this - This only works for a sketch which is saved to someone's account, and thus has a sketchId. If a non-logged in user tries to use this on the default sketch provided on the home page, it doesn't work, since it does not have any sort of url like https://preview.p5js.org/USERNAME/sketches/SKETCHID/worker.js to fetch the worker file from. (I believe this issue is beyond just web workers, it will affect anytime a file is 'fetch'ed from JavaScript)

I am unsure what the general solution for this issue is - somehow replace file path strings with Blob URLs? cc @raclim

This is a great catch! I'm not entirely sure yet what might be the best solution for it either yet, but I feel like Blob URLs make sense to me so far as a simpler fix and could be worth a shot! We do have an area where we're creating them within the editor for the Preview.

Since this seems like it might be something beyond web workers, we can merge your PR and create a new issue dedicated to this if that sounds good?

dipamsen

dipamsen commented on Mar 25, 2025

@dipamsen
Contributor

@raclim makes sense!

raclim

raclim commented on Mar 25, 2025

@raclim
Collaborator

Awesome! I just merged this in, the next set of changes should be out by sometime next week!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugError or unexpected behaviors

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @quarks@ksen0@raclim@dipamsen@Sanjai-Shaarugesh

      Issue actions

        'Web workers' do not work in editor · Issue #3414 · processing/p5.js-web-editor