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

在Chrome UserScript中实现MQTT消息拉取的正确方法及require报错解决

解决Chrome UserScript中使用require('mqtt')出现的"require is not defined"错误

问题原因

Chrome UserScript运行在浏览器环境中,没有Node.js的require函数,你尝试使用的是mqtt包的Node.js版本,无法直接在浏览器里运行。

解决方案

1. 引入浏览器兼容的mqtt版本

在UserScript的元数据中添加@require指令,引入mqtt的UMD(通用模块定义)版本,这个版本会将mqtt挂载为全局变量:

// ==UserScript==
// ... 其他元数据 ...
// @require      https://unpkg.com/mqtt/dist/mqtt.min.js
// ==/UserScript==

2. 修改代码移除require调用

删除var mqtt = require('mqtt')这一行,直接使用全局的mqtt对象即可。

3. 处理ESLint报错(可选)

如果ESLint仍然提示mqtt is not defined,可以在脚本开头添加全局变量声明:

/* global mqtt */

或者在你的ESLint配置文件中添加:

{
  "globals": {
    "mqtt": true
  }
}

修改后的完整代码示例

// ==UserScript==
// @name         MQTT Gmail Trigger Script
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Trigger script via MQTT when Gmail with keywords arrives
// @author       You
// @match        *://*/*
// @require      https://unpkg.com/mqtt/dist/mqtt.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    console.log(`Script started`);

    const client = mqtt.connect('mqtt://broker.hivemq.com');
    console.log(`Script connected`);
    textToSpeech("Starting");

    client.on('connect', function () {
        client.subscribe('thescriptthing/newemail', function (err) {
            if (!err) {
                console.log('Subscribed to topic');
            }
        });
    });

    function textToSpeech(text) {
        // 示例文本转语音实现
        const utterance = new SpeechSynthesisUtterance(text);
        window.speechSynthesis.speak(utterance);
    }
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:51:00