当页面改变时,Tampermonkey播放声音?

时间:2018-05-10 08:19:14

标签: javascript google-chrome userscripts page-refresh tampermonkey

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

这是我目前收集的代码,但我仍需要一些东西才能让它正常运行:

// ==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()

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

我一直在使用这个帖子作为指南:How to monitor a static HTML page for changes with Greasemonkey? Use a hash?但我不太确定哪种方法效果最好。任何和所有的建议将深表感谢。提前谢谢。

1 个答案:

答案 0 :(得分:2)

根据我的经验,您要检查的是特定元素的更改,而不是整个页面的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();
}

您将不得不使用某种持久性存储,我想您可以为此使用localStorage。参见HTML5 Web Storage