Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call chrome.alarms.create() from a content script

I'm developing a Chrome extension right now.

My problem is that when I call chrome.alarms.create(), I get the following error:

Uncaught TypeError: Cannot read property 'create' of undefined 

I have these files in my extension package:

manifest.json

{   
    "manifest_version": 2,
    "name": "Tool",
    "version": "1.0",
    "background": {
        "scripts": ["background.js"]
    },
    "permissions": ["background", "tabs", "webNavigation", "alarms"]
}

myscript.js

chrome.alarms.create("aaa", {"when":Date.now()+5000});

chrome.alarms.onAlarm.addListener(function(alarm){
  console.log("hello");
});

background.js

chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "myscript.js"});
});

When I call chrome.alarms.create() in background.js, it works fine. But, when I call the function in myscript.js, it causes the error.

What is the cause and how can I fix this problem?

like image 450
W3Q Avatar asked Dec 12 '25 01:12

W3Q


1 Answers

You can't access most Chrome APIs from a content script. You will need to use the Messaging API to send a message to the background page which can then call the Alarms API.

https://developer.chrome.com/extensions/messaging https://developer.chrome.com/extensions/content_scripts

like image 165
Daniel Herr Avatar answered Dec 13 '25 17:12

Daniel Herr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!