0

I am here asking how is it possible for my chrome extension to be able to "survive" throughout the user refreshing the page and changing page after selecting a feature.

For an example let's use a rather generic background color changing setting which changes the background color of a desired site. Once ticking the enable box and having the background changed to the option selected, it does not stay persistent after changing page or refreshing. I am here asking if someone could possibly help me with some sort of helpful resources which are more helpful than the developer.chrome site.

EDIT: for much better example of my question which is my bad. If anyone of you are aware of such extensions like "BetterTTV" for Twitch, it has a menu of options. One of these options is the "night" option which mentioned prior turns the entire site to "night colors" such as whites to black and black text to light. This option once enabled is seen through the entire site and even once Chrome is closed is still enabled to be producing changes next time opened. If i am correct in understanding what has been said, using Chrome storage will preserve such actions enabled by the user to be produced on the page till disabled.

Thank you.

  • A content script can survive for the same time that a webpage remains in the tab (i.e. not through refresh, or change to a new page). You can not make this longer. A background script can exist for the time that Chrome is running from starting Chrome through exiting. If you want to save settings, you can use [`chrome.storage`](https://developer.chrome.com/extensions/storage), or store the setting in the background page. You can then read the settings, or get them from the background page, when your content script starts again when the page is refreshed, or the user navigates to a new page. – Makyen Nov 04 '16 at 05:09
  • @Makyen Throughout current extensions, It is seen that you can enable a certain "night" mode which turns an entire site inverted colors. Instead of the actions of the extension being on a single page and like it never happened on the next. Using what you've suggested, does this do that? – SomeDisplayName Nov 04 '16 at 05:44
  • It depends on what you program. I'm really not sure what you are asking with that comment. If you are changing a setting in a content script it will live only as long as the content script unless you get the information somewhere will it will persist longer. That means `chrome.storage` or [messaging the information to a background script](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#Communicating_with_background_scripts). Either way, if you want to have the setting active when the content script next runs (refresh, navigating) you will have to get the setting back. – Makyen Nov 04 '16 at 05:50
  • How best to organize this depends on what you are doing. To go further really requires more information from you (e.g. code that shows what you are doing). There are many examples around of having settings persist, although usually not changed from a content script. Settings are mostly changed from [options pages](https://developer.chrome.com/extensions/optionsV2), popups, etc. – Makyen Nov 04 '16 at 05:54

1 Answers1

1

A content script can survive for the same time that a webpage remains in the tab (i.e. not through refresh, or navigating to a new page). You can not make this longer. A background script can exist for the time that Chrome is running from starting Chrome through exiting. If you want to save settings, you can use chrome.storage, or store the setting in the background page. You can then read the settings, or get them from the background page, when your content script starts again when the page is refreshed, or the user navigates to a new page. Using chrome.storage will allow you to persist the option until turned off. Using chrome.storage, even if Chrome is exited and restarted later, the option information will still be available. If you just store the data in a variable in the background page, it will not persist through exiting and restarting Chrome.

If you are changing a setting in a content script it will live only as long as the content script unless you get the information somewhere will it will persist longer. That means chrome.storage or messaging the information to a background script. Either way, if you want to have the setting active when the content script next runs (refresh, navigating) you will have to get the setting back (e.g. reading from chrome.storage or receiving a message from a background script).

In general, changing options in the content script is, probably, not a good idea. It is uncommon for such to be done in the content script. On the other hand, depending on what you are doing, changing some of your extension's options in a content script may be the most appropriate.

How best to organize this depends on what you are doing. To go further really requires more information from you (e.g. code that shows what you are doing). There are many examples around of having settings persist, although usually not changed from a content script. Settings are mostly changed from options pages, popups, etc.

If your function is as simple as "ticking the enable box and having the background changed to the option selected", having the selection take place in the content script is not a good idea. In that case, you should have a browser_action button which is either a toggle, or that brings up a popup where a checkbox could be ticked (if you have multiple options). The background script would then inject the content script using chrome.tabs.executeScript() only when the feature was enabled.

Update:
Based on the new information you have added to your question, it sounds like you should use a popup which will allow you to have multiple options, or a list of sites on which your add-on is enabled. If you are looking for an example, you can take a look at the Chrome developer options page example. You can have that as a popup with a `browser_action button in addition to being an options page by adding the following to your manifest.json

"browser_action": {
    "default_icon": {
        "48": "myIcon.png"
    },
    "default_title": "Show panel",
    "default_popup": "options.html"
},

If interested, my answer to this question shows using a single page as both an options page and popup. It shows how to get the data from the options page into chrome.storage and read it back. It is a bit more complicated than potentially desired as it shows four slightly different methods of communicating the information from the popup to a background page. It is tested and working in both Chrome and Firefox.

Here is an example of reading data (useDirect and emailAddress) from chrome.storage and placing the information in the DOM (to show the current value on an options page/popup):

// Restores select box and input using the preferences
// stored in chrome.storage.
function useStoredOptionsForDisplayInDOM() {
    chrome.storage.local.get({
        useDirect: 0,
        emailAddress: '',
        enabled: false
    }, function(items) {
        //Store retrieved options as the selected values in the DOM
        document.getElementById('useDirect').value = items.useDirect;
        document.getElementById('email').value = items.emailAddress;
        document.getElementById('enabled').checked = items.enabled;
    });
}

This is how those same values are stored in chrome.storage:

function saveOptions() {
    let useDirectValue = document.getElementById('useDirect').value;
    useDirectValue = +useDirectValue; //Force to number, not a string
    let email = document.getElementById('email').value;
    let functionEnabled = document.getElementById('enabled').checked;
    chrome.storage.local.set({
        useDirect: useDirectValue,
        emailAddress: email,
        enabled: functionEnabled
    });
}

And the <body> of the HTML:

<body>
    <div id="optionsArea">
        Use direct method:
        <select id="useDirect">
            <option value="0">Option 0</option>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">option 3</option>
        </select>
        <div>Email:
            <input id="email"></input>
        </div>
        <label>
            <input type="checkbox" id="enabled">
            Enable functionality.
        </label>
    </div>
   <script src="options.js"></script>
</body>
Community
  • 1
  • 1
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • Having the extension only produce results such as changing the background color when such option is enabled and not when disabled is exactly what I am looking towards figuring out. Keeping such a thing throughout the site rather than the current page activated on is what I am trying to seek out. – SomeDisplayName Nov 04 '16 at 06:35
  • @Fearcustard, On throughout the *website* (domain?), or on for all sites until turned off? On only during this visit to the website, or on during all visits to the website until turned off? – Makyen Nov 04 '16 at 06:41
  • On the current given website for example (stackoverflow), the user will have the option to with the running example change the background and have it such as that until they disable it. Keeping it active throughout page changes and closing the site. – SomeDisplayName Nov 04 '16 at 06:50
  • @Fearcustard, I added some more information about popups and options pages with pointers to a couple of examples. In addition to explicitly stating that `chrome.storage` persists over exiting Chrome and restarting. – Makyen Nov 04 '16 at 06:58
  • So If I feel you are leading me in the right direction, this use of options and chrome storage will have the user enable an option via like a tick box or button and will keep the actions of the background change enabled on the site until disabled? – SomeDisplayName Nov 04 '16 at 07:08
  • @Fearcustard, `chrome.storage` will persist the information that the option is enabled until such time as the user disables it. Obviously, it is up to the other parts of your extension to read that information and perform the task that the user indicated was enabled. – Makyen Nov 04 '16 at 07:11
  • With this chrome.storage being used to preserve such user options on the site until they're disabled by the same choice, It doesn't hurt to ask if you've got any recommended places on the subject before I go to try the use of chrome storage and thank you for your help. – SomeDisplayName Nov 04 '16 at 07:27
  • @Fearcustard, I've added some brief code examples for reading and storing to `chrome.storage`. In addition to the links I have provided in the answer and comments, I would suggest that in addition to the documentation on `developer.chrome.com` you also look at the documentation for Firefox WebExtensions. WebExtensions is a port of the Chrome Extension APIs to Firefox. While WebExtensions is not as functional as Chrome, the documentation usually has more examples for each API method and may be easier to understand (at least in some cases).(continued) – Makyen Nov 04 '16 at 07:55
  • @Fearcustard, (continued) However, the [WebExtensions documentation]() is in flux right at the moment. If you see an JavaScript API page that shows `browser.[method name]` in the Syntax section, you will probably want to ignore that page as it will just [add confusion](http://stackoverflow.com/a/39548757/3773011). I'm not advocating also testing your code on Firefox (you can do so if you like). I'm just suggesting looking at the documentation for more explanation/examples. – Makyen Nov 04 '16 at 07:55