Chrome Development

Chrome extension’s background page top level variable access

So, this is my background script:


const state = {
    inActivity = false

const setActivity = (payload, sender, callback) => {
    state.inActivity = payload.inActivity;

chrome.runtime.onMessage.addListener(function(payload, sender, callback) {
    if (payload.fn in this) {
        this[payload.fn](payload, sender, callback);

What I’m trying to do, so far without success, is set/change the value of the inActivity property (state.inActivity) by sending messages from my content script, like so:


    fn: 'setActivity',
    inActivity: true

However, I haven’t been able to find out state’s scope, or where it is stored, so I can reference it.

So far, this[setActivity] === undefined, window.setActivity === undefined, and globalThis.setActivity === undefined.

So, the question is: how can I call setActivity, or any other function, using the string parameter passed from my content script?

It is important to call it from the string this[payload.fn](...), passed as a parameter inside content script’s message, because it won’t be the only message available. This way I can have a single generic listener for all methods.

Leave a Reply

Your email address will not be published. Required fields are marked *