title: Chrome Extension: Play a notification sound when a web page element content changes
body: <p>I want to monitor a dynamically changing value on a web page with a Chrome extension (only for my own use) and play a notification sound and display an alert when that value changes. This page is not necessarily in the active tab.</p>
  
  <p>I have the following code so far, the only thing I need to do is to trigger the <strong>background.js</strong> when the value changes. My question is how to do that.</p>
  
  <p><strong>manifest.json</strong></p>
  
  <pre><code>{
      "manifest_version": 2,
      "name": "Example Website Notifications",
      "description": "Displays notifications on Example Website.",
      "version": "1.0",
  
      "background": {
          "scripts": ["background.js"],
          "persistent": false
      },
  
      "content_scripts": [{
          "matches": ["https://www.example.com/*"],
          "js": ["jquery.js", "content.js"]
      }]
  }
  </code></pre>
  
  <p><strong>content.js</strong></p>
  
  <pre><code>var value = $('#element').html();
  
  window.setInterval(function() {
      var newValue = $('#element').html();
      if (newValue != value) {
          /* Run code in background.js */
          value = newValue;
      }
  }, 5000);
  </code></pre>
  
  <p>I am checking the value in intervals of 5s. If there is a way to "know" when the value change happens, instead of checking every 5s, I am also open to that.</p>
  
  <p><strong>background.js</strong></p>
  
  <pre><code>var sound = new Audio('sound.mp3').play();
  alert('Value Changed');
  </code></pre>
  
  <p>The reason I have <strong>alert()</strong> in addition to the sound notification is so that the browser window icon will blink in the task bar, in case I miss hearing the sound alert.</p>
  
  <p>When I tested background.js to see if the audio plays, the alert is displayed first, then the audio is played after clicking OK on the alert, even though the line to play the audio file comes before. Any ideas why that happens?</p>