You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS与Tampermonkey实现Instagram私信新消息音效提醒

Instagram私信新消息提示音Tampermonkey脚本修复方案

原脚本核心问题

  1. DOM选择器过时:Instagram前端类名动态生成,.direct-thread、.direct-thread-message-renderer这类旧类早已废弃,导致无法捕获消息容器和新消息。
  2. 未过滤自身消息:会把自己发送的消息误判为新消息触发提示。
  3. 容器加载时机错误:页面未完全加载时脚本就执行,导致监听无法绑定到聊天容器。
  4. 音频重复加载:每次播放都重新创建Audio对象,重复请求资源导致延迟。

修复后的完整脚本

// ==UserScript==
// @name Instagram私信新消息提示音
// @namespace https://www.instagram.com/
// @description 收到Instagram新私信时播放提示音
// @match https://www.instagram.com/direct/*
// @version 1.1
// @grant none
// ==/UserScript==

(function() {
    'use strict';

    // 预加载提示音,避免重复请求
    const notificationSound = new Audio('https://cdn.discordapp.com/attachments/550960750349385730/1074758001048690698/pristine-609.mp3');
    notificationSound.preload = 'auto';

    function playNotificationSound() {
        // 克隆音频对象解决重复播放限制
        const soundClone = notificationSound.cloneNode();
        soundClone.play().catch(err => console.log('提示音播放失败:', err));
    }

    function setupMessageObserver() {
        // 定位当前稳定的聊天消息容器
        const chatContainer = document.querySelector('div[role="dialog"] div.x9f619.x1n2onr6.x1ja2u2z');
        if (!chatContainer) {
            // 容器未加载,1秒后重试
            setTimeout(setupMessageObserver, 1000);
            return;
        }

        const observer = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType !== Node.ELEMENT_NODE) return;
                    
                    // 过滤自己发送的消息(通过自身消息的专属类判断)
                    const isSelfMessage = node.querySelector('.x1qjc9v5.x1oa3qoh.x1nhvcw1');
                    if (!isSelfMessage) {
                        playNotificationSound();
                    }
                });
            });
        });

        observer.observe(chatContainer, {
            childList: true,
            subtree: true
        });
    }

    // 页面加载完成后启动监听
    window.addEventListener('load', setupMessageObserver);
})();

关键修改说明

  • 更新DOM选择器:改用div[role="dialog"] div.x9f619.x1n2onr6.x1ja2u2z定位聊天容器,该结构相对稳定(若后续Instagram更新DOM,需通过开发者工具重新获取新选择器)。
  • 过滤自身消息:通过检查消息元素是否包含自身消息专属类,避免触发无效提示。
  • 音频预加载优化:提前创建Audio对象并预加载,通过克隆对象解决浏览器重复播放限制。
  • 动态等待容器加载:初始找不到容器时自动重试,确保监听能正确绑定。
  • 缩小生效范围:将@include改为@match https://www.instagram.com/direct/*,仅在私信页面运行脚本。

额外提示

  • 若后续脚本失效,打开浏览器F12开发者工具,找到新消息元素的类名或结构,替换对应选择器即可。
  • 提示音链接可替换为任意支持跨域的音频资源。

内容的提问来源于stack exchange,提问作者Legend_recalls

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:40:38