Chrome 扩展后台脚本有时在安装或更新后不运行

Ham*_*and 6 google-chrome-extension

我最近收到有关我开发的 chrome 扩展程序的报告,该扩展程序在更新或全新安装后停止工作。后台脚本似乎根本没有启动。

  • 从内容脚本发送给它的消息没有响应。
  • 任务管理器中没有它的进程。
  • 从 chrome://extensions 打开后台页面不会在控制台中显示任何活动,也不会显示任何源文件。
  • 分析、内存快照按钮被禁用。

一旦出现此问题,即使在重新加载或卸载/重新安装扩展程序后,chrome 配置文件也仍然存在。

重新启动 chrome 可以解决问题。

该问题已在 chrome v79 上看到。但我不能肯定地说它是这个版本独有的,因为这个问题很难重现,而且似乎是随机的。

有没有人看到过这样的问题,或者有任何想法要寻找什么?我很高兴用我拥有的任何新信息或您需要的任何信息更新我的问题。

编辑:

这是我的webNavigation监听器,用于注入内容脚本。这个处理程序连接在后台脚本的“根”上下文中(不是在事件处理程序中异步)

chrome.webNavigation.onCompleted.addListener((details) ? { 
   if(details.frameId === 0) { 
     injectScript( 
       'js/contentScript.js', 
       details.tabId, 
       details.frameId, 
       details.url 
     ).catch((e) ? {}); 
   }
}
Run Code Online (Sandbox Code Playgroud)

injectScript功能如下

export const injectScript = ƒ (scriptPath,tab,frame,tabUrl) { 
  return new Promise((res,rej) ? {  
    let options = { 
      file : scriptPath, 
      allFrames : false, 
      frameId : frame, 
      matchAboutBlank: false, 
      runAt : 'document_idle', 
    }; 
    const cb = ƒ () { 
      if (chrome.runtime.lastError) { 
        let err = new Error('Could not inject script'); 
        capture(err,{ 
          ...options, 
          tabUrl, 
          lastError : chrome.runtime.lastError.message, 
        }); 
        rej(err); 
      }else{ 
        res(); 
      } 
    }; 
    if (tabUrl.indexOf('.salesforce.com') !== -1) { 
      window.setTimeout(() => { 
        chrome.tabs.executeScript(tab,options,cb); 
      },500); 
    }else{ 
      chrome.tabs.executeScript(tab,options,cb); 
    } 
  }); 
};
Run Code Online (Sandbox Code Playgroud)

上面请注意,该capture函数向后端报告错误,我也看不到它在那里报告。如上所述,无法在代码中添加断点,因为后台页面中没有显示源。

Bot*_*Liu 0

医生

后台 Service Worker 在需要时加载,在空闲时卸载。

https://developer.chrome.com/docs/extensions/mv3/service_workers/

您可以使用以下方法:

// Keep heartbeat
let heartTimer;
const keepAlive = () => {
    heartTimer && clearTimeout(heartTimer);
    heartTimer = setTimeout(() => {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            console.info('[heartbeat]')
            tabs.length && chrome.tabs.sendMessage(
                tabs[0].id,
                { action: "heartbeat" }
            );
        });
        keepAlive();
    }, 10000);
};
keepAlive();
Run Code Online (Sandbox Code Playgroud)