Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tampermonkey play sound when page changes?

Basically, there is a specific website I visit that I keep a userscript auto-refresh set on a timer. This specific page changes content every now and then upon being refreshed. I want a sound to be played whenever the page gets refreshed and any page changes occur.

Here's the code I've currently gathered, but I still need a few things to get it running properly:

// ==UserScript==
// @name     Auto-Refresh
// @include  https://www.prolific.ac/studies
// ==/UserScript==

//--- https://stackoverflow.com/questions/25484978/i-want-a-simple-greasemonkey-script-to-reload-the-page-every-minute
setTimeout(function(){ location.reload(); }, 20*1000);

var player = document.createElement('audio');
player.src = 'https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3';
player.preload = 'auto';

  // Play a sound with condition and then player.play()

So basically the rest of the script would be "if page change occurs (after refresh), then play sound." This is where I'm having trouble.

I've been using this thread as a guide: How to monitor a static HTML page for changes with Greasemonkey? Use a hash? But I'm not quite sure which method would work best. Any and all advice would be deeply appreciated. Thanks in advance.

like image 679
theCrabNebula Avatar asked May 10 '18 08:05

theCrabNebula


2 Answers

In my experience you want to check for changes in specific elements, not the HTML of the entire page because there are often technical parts of the page that will change (timestamps, counters, random generated IDs, ads). So I have used jQuery to find the pieces which I then check for changes.

I guess you could check for changes in entire parts of page by doing something like this:

var player = document.createElement('audio');
player.src = 'https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3';
player.preload = 'auto';

// First you store the content
var initialContent = $('.articles-section').html();

// Then next time you compare that content to the newly retrieved content
var newContent = $('.articles-section').html();
if (newContent !== initialContent) {
    player.play();
}

You will have to use some kind of persistent storage, I guess you can use localStorage for that. See HTML5 Web Storage.

like image 193
TheStoryCoder Avatar answered Nov 09 '22 15:11

TheStoryCoder


This part

var player = document.createElement('audio');
player.src = 'https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3';
player.preload = 'auto';

only worked for me when I did

player.play() instead of player.preload = 'auto'

like image 1
MKKirk Avatar answered Nov 09 '22 17:11

MKKirk