0xsh
0xsh

Reputation: 1595

How to run chrome extension in background automatically?

I want to create a chrome extension. I have a popup.html and also a background.js file. I want to create a countdown timer and also want it to run automatically. but the background.js file cannot access the popup.html. How to run scripts in backgrounds and automatically change the DOM?

popup.html:

<span class="time">20:00</span>
<script src="background.js"></script>

background.js:

startTimer = (duration, display) => {
  let time = duration, minutes, seconds;


setInterval(() => {
  minutes = parseInt(time / 60, 10);
  seconds = parseInt(time % 60, 10);

  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  display.innerHTML = `${minutes}:${seconds}`;
  if (--time < 0) {
    time = duration;
  }
 }, 1000);
}

window.onload = () => {
  let duration = 60 * .1, display = document.querySelector('.time');  
  startTimer(duration, display);
}

Upvotes: 2

Views: 4489

Answers (1)

woxxom
woxxom

Reputation: 73836

Currently your script is just a normal script that runs inside the popup page.
Just because it's named background.js it doesn't magically become a background script.

A real background script must be declared in manifest.json:

"background": {
  "scripts": ["background.js"],
  "persistent": false
}

It creates a separate hidden background page (or event page when using "persistent": false) where that background script will run and will have direct access to DOM of that background page (not to the popup). To inspect/debug the background script click the background page on chrome://extensions page when it's in developer mode: more info.

Another problem is that the popup exists only when it's shown so you will have to find another way of showing the timer. For example a separate small window (opened via chrome.windows.create) or a small text badge on the extension icon (set via chrome.browserAction.setBadgeText), for which you can find examples by googling.

Upvotes: 3

Related Questions