shuboy2014 shuboy2014 - 3 months ago 14x
jQuery Question

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?

Xan Xan

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 API instead of localStorage, which comes with a event.