How to use chrome.alarms for Google Chrome extension

前端 未结 2 1083
长情又很酷
长情又很酷 2020-12-13 16:10

manifest.json

{
    \"manifest_version\": 2,
    \"name\": \"App name\",
    \"description\": \"Description goes here\",
    \"version\": \"         


        
相关标签:
2条回答
  • 2020-12-13 16:56

    Here is the simplest working example I can think of, warning it is very annoying as when the alarm is on it alerts "Beep" every 12 seconds. It uses a popup browser action to switch the alarm on and off.

    manifest.json

    {
      "manifest_version": 2,
    
      "name": "Alarm test",
      "description": "This extension alarms.",
      "version": "1.0",
    
      "permissions": [
        "alarms"
      ],
    
      "background": {
        "scripts": ["eventPage.js"],
        "persistent": false
      },
    
      "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
      }
    }
    

    popup.html

    <!doctype html>
    <html>
    <head>
    <title>Alarms Popup</title>
    
    <script src="popup.js"></script>
    </head>
    <body>
    <a href="" id="alarmOn">ON</a>
    <a href="" id="alarmOff">OFF</a>
    </ul>
    </body>
    </html>
    

    popup.js

    var alarmClock = {
    
            onHandler : function(e) {
                chrome.alarms.create("myAlarm", {delayInMinutes: 0.1, periodInMinutes: 0.2} );
                        window.close();
            },
    
            offHandler : function(e) {
                chrome.alarms.clear("myAlarm");
                        window.close();
            },
    
            setup: function() {
                var a = document.getElementById('alarmOn');
                a.addEventListener('click',  alarmClock.onHandler );
                var a = document.getElementById('alarmOff');
                a.addEventListener('click',  alarmClock.offHandler );
            }
    };
    
    document.addEventListener('DOMContentLoaded', function () {
        alarmClock.setup();
    });
    

    And the important bit in eventPage.js

    chrome.alarms.onAlarm.addListener(function(alarm) {
      alert("Beep");
    });
    
    0 讨论(0)
  • 2020-12-13 17:09

    You didn't create any alarm, so no onAlarm event will be fired.

    Create an alarm with chrome.alarms.create. Note: you should do it in the chrome.runtime.onInstalled event.

    0 讨论(0)
提交回复
热议问题