shuboy2014
shuboy2014

Reputation: 1370

How can I run background script dynamically in chrome extension?

I want to run background script dynamically only when it needs to.

My background script creates a context menu based on an array which is stored in localStroage. Background script only runs once on loading, and I want to run the script again when user update an array in localStroage, how can I do that?

Upvotes: 1

Views: 289

Answers (1)

Xan
Xan

Reputation: 77523

Event pages were created specifically to address "background pages that do nothing most of the time" problem. They are unloaded after a few seconds of inactivity, and run again when any of the events for which handlers are registered occur.

Read the documentation - there are nuances as to how they must be structured. Also, specifically for context menus you can't use onclick parameter and must use the chrome.contextMenus.onClicked event instead.

You can use Messaging to wake up your event page from other extension contexts. Also, consider using chrome.storage API instead of localStorage, which comes with a chrome.storage.onChanged event.

Upvotes: 1

Related Questions