Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

javascript - How to use chrome.alarms for Google Chrome extension

manifest.json

{
    "manifest_version": 2,
    "name": "App name",
    "description": "Description goes here",
    "version": "1.0",    
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": [
        "tabs",
        "alarms"
    ],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    }
}

I trying to create a function to make a popup "great" every minute like this:

chrome.alarms.onAlarm.addListener(function(){
        alert('great');
    });

Could someone please tell why is it not triggering that alert. I check the console, no error was displayed. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...