Reputation: 1424
Pretend I have a chrome extension that has a word of the day. Each day I have a new word and my extension highlights that word on any page loaded in the browser that day. I could have a rotating list of words, but I want to maintain that list on my website so I can easily change it based on news or current events.
How could I make my extension get the contents of a file on my server every X hours and save that as a variable for future use?
Upvotes: 1
Views: 240
Reputation: 3292
You need to keep something like a timer for requests in a background.js. As Daniel suggested, easiest way to do that is using the chrome.alarms API.
For example:
manifest.json
{
"manifest_version": 2,
"name": "My Extension",
"version": "1.0.0",
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"permissions": [
"alarms",
"storage"
]
}
background.js
chrome.alarms.onAlarm.addListener(alarm => {
fetch('http://your_website_here')
.then(response => response.text())
.then(textResponse => {
chrome.storage.local.set({data: textResponse});
})
.catch(e => {console.error(e)})
});
chrome.alarms.create('fetch_data', {
periodInMinutes: 60 //every hour
});
I suggest you to use the chrome.storage API, to store your data. You can retrieve it later from content-script.
Upvotes: 2