Unable to run background task

Hi
when I run my runner.js file, i get Uncaught (in promise) Error: Error: public/runner.js from logcat

// runner.js
addEventListener('fetchTest', async (resolve, reject, args) => {
    console.log(JSON.stringify({ EVENT: 'fetchTest' }));

    try {
        const res = await fetch('https://randomuser.me/api/');
        if (!res.ok) {
            throw new Error('Could not fetch user');
        }
        const result = await res.json();
        resolve(result['results'][0]);
    } catch (err) {
        console.log(JSON.stringify({ ERROR1: 'test' }));
        reject(err);
    }
});

addEventListener('test', async (resolve, reject, args) => {
    console.log(JSON.stringify({ EVENT: 'test' }));

    try {
        console.log(JSON.stringify({ test: 'test' }));
        resolve();
    } catch (err) {
        console.log(JSON.stringify({ ERROR2: 'test' }));
        reject(err);
    }
});

capacitor.config.ts

const config: CapacitorConfig = {
...
plugins: {
        BackgroundRunner: {
            label: 'com.va.mozatunes.app.task',
            src: 'runner.js',
            event: 'test',
            repeat: true,
            interval: 5,
            autoStart: true,
        },
    },
...
}

//my code

await BackgroundRunner.dispatchEvent({
                label: 'com.my.app.task',
                event: 'test',
                details: {},
            });
1 Like

I have not used the Background plugin but I would guess the registered label com.va.mozatunes.app.task needs to match the label in dispatchEvent. Right now you have com.my.app.task.

I actually forgot to rename it for the example, but inside my app it’s the same name.

Me too so i used @anuradev/capacitor-background-mode - npm

this plugin keeps the application in the foreground. It tricks the operating system into believing that the application is still in the foreground, allowing operations to be performed without operating system crashes.