页面更改时 Tampermonkey 播放声音?

the*_*ula 5 javascript google-chrome userscripts page-refresh tampermonkey

基本上,我访问了一个特定的网站,我在计时器上设置了用户脚本自动刷新。该特定页面在刷新时不时更改内容。我希望在页面刷新和发生任何页面更改时播放声音。

这是我目前收集的代码,但我仍然需要做一些事情才能使其正常运行:

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

//--- /sf/ask/1783948491/
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()
Run Code Online (Sandbox Code Playgroud)

所以基本上脚本的其余部分将是“如果发生页面更改(刷新后),则播放声音。” 这是我遇到麻烦的地方。

我一直在使用此线程作为指导:如何使用 Greasemonkey 监视静态 HTML 页面的更改?使用哈希?但我不太确定哪种方法最有效。任何和所有建议将不胜感激。提前致谢。

The*_*der 5

根据我的经验,您希望检查特定元素的变化,而不是整个页面的 HTML,因为页面的技术部分通常会发生变化(时间戳、计数器、随机生成的 ID、广告)。所以我使用 jQuery 来查找我然后检查更改的部分。

我想您可以通过执行以下操作来检查页面整个部分的更改:

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();
}
Run Code Online (Sandbox Code Playgroud)

您将不得不使用某种持久存储,我想您可以使用localStorage它。请参阅HTML5 网络存储