Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - Published extension doesn't work with chrome API listeners inside onInstalled

I've just tested my Chrome addon https://chrome.google.com/webstore/detail/soft-screen/oecaicengbgemdbdklmajocogdjjgnda after installing it officially, i.e. via CWS (Chrome Web Store), but was suddenly surprised that it's not working. I've always used it by installing it locally in Dev mode, i.e. by copying the addon installed and located at {The Chrome directory}User DataDefaultExtensionsoecaicengbgemdbdklmajocogdjjgnda to another directory and then reinstall it by dragging it to the chrome://extension URL (while Developer mode is on). I then had to remove the key from its manifest.json and then disable the first one that was installed via CWS. I could toggle the extension between local Developer mode and CWS extension to prevent two conflicting identical extensions installed and enabled at once.

The difference is very conspicuous in which it does not work in using the CWS ("Add to Chrome") installation, but it simply works in local Developer mode.

Can you please help me out by doing the same as I did and may you be more knowledgeable than me so that I will be able to fix the bug and solve the problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a common problem: you're using a non-persistent background script ("persistent":false in manifest.json) and a chrome.runtime.onInstalled listener where you register some other listeners.

This is wrong because onInstalled event is triggered only on installs/updates for a published extension and it happens asynchronously, which is a problem because chrome API listeners must be registered synchronously when using a non-persistent background script, otherwise the event that woke the background script won't be dispatched to this listener i.e. the event will be lost.

It worked for you in developer mode only because reloading an extension is treated by Chrome as an update event reported in onInstalled. Or maybe you had devtools open for your background script which prevented it from unloading automatically.

TL;DR Solution:

Move chrome.browserAction.onClicked registration out of chrome.runtime.onInstalled:

chrome.runtime.onInstalled.addListener(function(info) {
  // code that should run on install/update
  // ...............
});

chrome.browserAction.onClicked.addListener(function(tab) {
  // code that should run on clicking the extension icon
  // ...............
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...