Search code examples
javascriptjquerygoogle-chromegoogle-chrome-extension

Google Chrome extensions : Alert when Modal/ popup closed


I created google chrome's extension for timer and alert. This will alert if users set time (Remind Time) is equal to current time. This is work fine but only if extension is open. I want to do that alert fire, when even extension not opened.

This is an open extension. alert fire only if extension is open.

enter image description here

Here is my code jquery code which check both time and fire an alert on condition.

window.setInterval(function(){

    // Get/Display CurrentTime

    $(document).ready(function(){
        // Check If Time set
        $("#RemindTime").text(localStorage.getItem("newtime"));
        var RemindTime = localStorage.getItem("newtime");
        RemindTime = RemindTime+":00";

        var today = new Date();
        var cHour = (today.getHours()<10?'0':'') + today.getHours();
        var cMin = (today.getMinutes()<10?'0':'') + today.getMinutes();
        var cSec = (today.getSeconds()<10?'0':'') + today.getSeconds();
        var currentTime = cHour+ ":" + cMin + ":" +cSec;
        $("#CurrentTime").text(currentTime);

        // Tell If Time Passed Or Not
        if(RemindTime == currentTime)
        {
            // Alert if set time is equal to current time
            alert("Your reminder is in progress");
            $("#status").text("Your reminder is in progress");
        }
        if(localStorage.getItem("newtime") < currentTime)
        {
            $("#status").text("Your reminder is over");
        }
        if(localStorage.getItem("newtime") > currentTime)
        {
            // Calculate Difference to be pass
            var start = currentTime;
            var end = localStorage.getItem("newtime");

            s = start.split(':');
            e = end.split(':');

            min = e[1]-s[1];
            hour_carry = 0;
            if(min < 0){
                min += 60;
                hour_carry += 1;
            }
            hour = e[0]-s[0]-hour_carry;
            diff = hour + ":" + min;

            $("#status").text("Your reminder will execute after "+hour+" Hour and "+min+" Min.");
        }

        // Set New Reminder time for new reminder
        $("#submit").click(function(){

            if($("#newtime").val())
            {
                var newtime = $("#newtime").val();
                localStorage.setItem("newtime", newtime+":00");
            }
            else
            {
                var newtime = currentTime;
                localStorage.setItem("newtime", newtime);
            }

            $("#RemindTime").text(newtime);
        });


    });
    }, 100);

HTML

  <body>
        <div class="container">
            Current Time : <span id="CurrentTime"></span>
        </div>
        <div class="container">
            Remind Time : <span id="RemindTime"></span>
        </div>
        <br><hr>
        <div class="container">
            <span id="status"></span>
        </div>
        <br><hr>
        <div class="container">
            Change Time : <input type="time" name="newtime" id = "newtime" />
            <br>
            <input type = "button" id="submit" value="Set Time"/>
        </div>
      </body>

manifest.json

  {
  "manifest_version": 2,

  "name": "Remind Me :) ",
  "description": "This extension shows a Simple Time Counter for slected time",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "background": {
    "scripts": ["popup.html"],
    "persistent": false
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

Solution

  • Use an Event page (you already have one but see the first point below) and alarms API:

    • I suggest having a separate background page file for the sake of clarity

    • manifest.json

        "background": {
            "scripts": ["eventPage.js"],
            "persistent": false
        },
        "permissions": [
            "alarms"
        ],
      
    • popup.js sends a message to the event page:

        // in 60 minutes
        chrome.runtime.sendMessage({name: "alarm 1", time: {delayInMinutes: 60}});
        // in 1 minute
        chrome.runtime.sendMessage({name: "alarm 2", time: {when: Date.now() + 1 * 60e3}});
      
    • eventPage.js:

        chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
            if (msg.time) {
                chrome.alarms.create(msg.name, msg.time);
            }
        });
      
        chrome.alarms.onAlarm.addListener(function(alarm) {
            alert(alarm.name + " fired, wake up!");
        });
      
    • Instead of alert() it might be better to use notifications API

    Examine the samples where you can also see how to organize communication between background (event) pages and other parts of the extension.

    Note: Once you've published the Chrome extension, the actual interval will be rounded up to 1 minute even if you set a smaller value like 5 seconds (5000ms).

    Source: https://developer.chrome.com/docs/extensions/reference/alarms/#method-create

    In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute.

    To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire.