Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox Web Extension "Can't access dead object" error

I was having trouble finding an up-to-date answer for this issue, and don't often have time to answer questions here so thought I'd post this so I can answer my own question since I figured out a solution.

I'm making a Web Extension for Chrome and Firefox. Firefox has this issue that when I call a background function that sets some data to a var in the background page from the options page JS, and then close the options page, I get the error "Can't access dead object" when the background code later tries to access the variable that was set. Here's the code:

options.js

formInOptions.addEventListener('submit', function(e){
    e.preventDefault();
    chrome.extension.getBackgroundPage().defaults({
        keyname:  e.target['form-field'].value
    }, function(){
        // data saved cb
    });
});

background.js

function defaults(oNewDefaults) {
    // Global oDefaults already exists, and trying to access this after the options page is closed causes the error.
    chrome.storage.local.get({
        config: {}
    }, function(data) {
        let config = data.config;
        config.defaults = config.defaults || {};
        config.defaults = Object.assign(config.defaults, oNewDefaults); // Merge incoming obj into existing obj
        chrome.storage.local.set({
            config: config
        }, function() {
            oDefaults = config.defaults;
        });
    });
};
like image 865
tripRev Avatar asked Oct 29 '22 03:10

tripRev


1 Answers

To prevent the error, my solution was to stringify and then re-parse the incoming JS obj, like this: config.defaults = Object.assign(JSON.parse(JSON.stringify(config.defaults)), JSON.parse(JSON.stringify(oNewDefaults)));

like image 66
tripRev Avatar answered Nov 12 '22 12:11

tripRev