首页 > 解决方案 > 页面更改时 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()

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

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

标签: javascriptgoogle-chromeuserscriptspage-refreshtampermonkey

解决方案


根据我的经验,您希望检查特定元素的变化,而不是整个页面的 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 网络存储


推荐阅读