kd394
kd394

Reputation: 15

Make and reflect changes to popup.html in chrome extension

I am new to chrome extensions. I am trying to make a basic extension which updates the value to an input field in the popup page every few seconds. Here is my current code.

manifest.json

{
 "manifest_version": 2,
 "name": "Test extension",
 "version": "1",
 "browser_action": {
    "default_icon": "tl.png",
    "default_popup": "layout.html"
 },
 "background": {
    "scripts": ["jquery-3.2.1.min.js","addvalues.js"],
    "persistent": false
 },

 "permissions": [
        "alarms",
        "tabs",
        "webNavigation"
   ]

}   

layout.html

<html>
<head>
    <script src="jquery-3.2.1.min.js"></script>
    <script src="addvalues.js"></script>
</head>

<body>
    <label for="pfvalue"> Portfolio value </label>
    <input id="pfvalue" readonly style="border:0; color:#f6931f; font-weight:bold; padding-bottom: 10px;">

</body>
</html>

addvalues.js

$(function()
{
    var i=0;
    var portvalue;
    function getData()
    {    
        portvalue = i;                       
        $("#pfvalue").val(portvalue);
        i++;
        console.log(portvalue);
    }    

    getData();   
    chrome.alarms.create("fetch data",{periodInMinutes: 0.1});
    chrome.alarms.onAlarm.addListener(getData);        
});

When I keep the popup page open for long enough, the input value does change like it is supposed to. But when I close it and then open it again, the popup page resets to the initial state of showing 0. I am not able to figure out why this happens.

The console shows the right value of portvalue (i.e. the one that gets updated every 6 seconds).

Thanks in advance.

Upvotes: 0

Views: 1472

Answers (1)

woxxom
woxxom

Reputation: 73616

  1. Make sure to read the extension architecture overview: the popup is a separate page that exists only while shown. To view its devtools and console rightclick the popup and click Inspect.
  2. A background/event page is a separate, hidden page with its own DOM so no need to load jQuery there.
  3. Your background page can increment the value and store it via chrome.storage.local.set
  4. Your popup.js (a different script) can use chrome.storage.local.get on startup and chrome.storage.onChanged to detect the changes
  5. It's meaningless to use an event page ("persistent" : false in your manifest.json) if you wake it up every 6 seconds because an event page is unloaded automatically after 5 seconds since its last activation, meaning your event page currently gets unloaded every 6 seconds for just 1 second. That's a waste of the computer resources: every time it loads the browser needs to parse it, compile it, optimize it and so on.

Upvotes: 2

Related Questions