How to avoid “Extension context invalidated” errors when messaging AFTER an Extension update?

前端 未结 5 1939
一整个雨季
一整个雨季 2020-12-13 04:32

I am trying to create a smooth experience for users of my Chrome Extension after I release updates.

I reinject my content script on an update of the app, and my func

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 05:07

    Try this in your background script. Many of the old methods have been deprecated now, so I have refactored the code. For my use I'm only installing single content_script file. If need you can iterate over chrome.runtime.getManifest().content_scripts array to get all .js files.

    chrome.runtime.onInstalled.addListener(installScript);
    
    function installScript(details){
        // console.log('Installing content script in all tabs.');
        let params = {
            currentWindow: true
        };
        chrome.tabs.query(params, function gotTabs(tabs){
            let contentjsFile = chrome.runtime.getManifest().content_scripts[0].js[0];
            for (let index = 0; index < tabs.length; index++) {
                chrome.tabs.executeScript(tabs[index].id, {
                    file: contentjsFile
                },
                result => {
                    const lastErr = chrome.runtime.lastError;
                    if (lastErr) {
                        console.error('tab: ' + tabs[index].id + ' lastError: ' + JSON.stringify(lastErr));
                    }
                })
            }
        });    
    }
    

提交回复
热议问题