如何在 jQuery ajax 中的用户代理中添加附加信息?

How to add additional information in User-agent in jQuery ajax?

我读到了这个 here and here,但我仍然不知道如何在 jQuery ajax 中做到这一点。我尝试了我链接的问题的答案之一中的代码,但它丢弃了用户代理覆盖:

$.ajax({ 
    url: "http://blablabla.com/",
    dataType:'html', 
    beforeSend: function (req) {
        req.setRequestHeader('User-Agent', 'https://graphicdesign.stackexchange.com/users/69916/vikas');
    },
    error: function() { alert("No data found");},
    success: parseResult
});

我当前发送的用户代理字符串是这样的:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.40 Safari/537.36 Edg/92.0.902.9

我也想添加我的其他 SE 配置文件 URL,其中 https://graphicdesign.stackexchange.com/users/69916/vikas

我想这样做是因为有人建议 here 以防你参与聊天机器人。

A simple example about how to put additional information, i.e., my profile URL in existing User-agent and send it using ajax to any api, would help.

jQuery使用XMLHttpRequest to send the request and is therefore subject to the same limitations and issues it has. In particular, when you call the setRequestHeader或提供一个headers配置选项,相应的XMLHttpRequest方法用于设置headers.

这就是 jQuery 在配置 object:

中所做的 under the hood
// Set headers
for ( i in headers ) {
    xhr.setRequestHeader( i, headers[ i ] );
}

您可能知道,setRequestHeader 方法的 the spec 算法的第 5 步说,如果 header 处于“禁止”状态,它应该 return headers" 列表:

  1. If name is a forbidden header name, then return.

这很重要,因为 User-Agent header 曾经在该列表中(Fetch 存储库中的 draft that made it forbidden is the one from September 2008). This is no longer the case (see the issue #37),但是,Chromium-based 浏览器(意味着您至少 Chrome 和 Edge 不走运)将静静地丢弃它(在 Fetch API 的情况下或抛出错误:

Refused to set unsafe header "User-Agent"

请参阅 MDN 参考中的以下说明:

The User-Agent header is no longer forbidden, as per spec — see forbidden header name list (this was implemented in Firefox 43) — it can now be set in a Fetch Headers object, or via XHR setRequestHeader(). However, Chrome will silently drop the header from Fetch requests (see Chromium bug 571722).

MDN 指的是被认为正在处理的错误 571722,因此事情可能会在不久的将来发生变化。