使用 GM_xmlhttpRequest 流式传输数据:缺少响应文本

问题描述 投票:0回答:1

我正在尝试通过

GM_xmlhttpRequest
接收带有 Tampermonkey (v4.18.1) 用户脚本的流媒体响应。我向请求对象的
onreadystatechange
属性添加了一个函数。我遇到的问题是中间响应中缺少
responseText
属性,即
readyState
3
。我只得到完整的、最终的回复内容,即
readyState
在哪里
4
.

这是一个 MWE 脚本:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.com/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=google.com
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';
    let button = document.createElement("input");
    button.setAttribute("type", "submit");
    button.setAttribute("value", "stream");
    button.style.position = "fixed";
    button.style.top = "20px";
    button.style.left = "20px";
    button.style.width = "400px";
    button.style.height = "400px";
    button.style.zIndex = 9999;
    button.addEventListener("click", () => {
        GM_xmlhttpRequest({
            method: "GET",
            url: "http://localhost:9297/stream",
            responseType: "blob",
            onreadystatechange: function(response) {
                console.log(response);
            }
        });
    });
    document.body.appendChild(button);
})();

我试过设置

responseType
为不同的东西(
stream
text
arraybuffer
),我其实不明白这个参数的意义是什么。打印在控制台中的状态变化之间有预期的 1 秒延迟,但我似乎无权访问中间响应内容,只能访问状态消息和标题等

我用作后端的是一个非常简单的 Flask 服务器:

from flask import Flask, Response
import json
import time

app = Flask(__name__)

@app.route('/stream')
def stream():
    def generate():
        yield json.dumps({ "foo": 1 })
        time.sleep(1)
        yield json.dumps({ "foo": 2 })
    return Response(generate(), mimetype="application/json")

app.run(port=9297)

我可以用

curl -N "http://127.0.0.1:9297/stream"
验证服务器,响应是

{"foo": 1}<one second pause>{"foo": 2}

如何使用 Tampermonkey 中的 xmlhttpRequest 从服务器获得中间响应,即

{"foo": 1}

javascript flask streaming tampermonkey userscripts
1个回答
0
投票

来自https://github.com/Tampermonkey/tampermonkey/issues/1278

当您使用

XMLHttpRequest
下载一些数据时,整个数据存储在内存中,直到请求完成并处理数据。

显然是由于

XMLHttpRequest
,与 Tampermonkey 无关。

使用

responseType: "stream"
和代码 here 结束工作。

© www.soinside.com 2019 - 2024. All rights reserved.