从Chrome扩展程序更改XMLHttpRequest中的User-Agent [英] Changing User-Agent in XMLHttpRequest from a Chrome extension
问题描述
我尝试从扩展中发送HTTP请求,在该扩展中我需要更改用户代理。
我的代码如下所示:
function getXMLHttpRequest(method,url,extraHeaders){
var xhr = new XMLHttpRequest();
xhr.open(method,url,true)
(extraHeaders中的var headerKey){
xhr.setRequestHeader(headerKey,extraHeaders [headerKey]);
}
return xhr;
}
// ....
getXMLHttpRequest(POST,....,{User-Agent:Blahblahblah})
然后,我收到错误拒绝设置不安全标题:UserAgent
我需要改变这种情况,因为我的后端需要有一个特殊的用户代理,是否可以通过扩展来实现?
我尝试了webRequest API,在发送请求之前更改头,但它表示它不能与扩展中的XMLHttpRequest一起使用,以防止锁定。
对于示例代码,请参阅将a自定义用户代理到特定的Google Chrome页面/标签。通过
XMLHttpRequest
发起的网络请求修改sub_frame至xmlhttprequest
p> 显然,为了防止死锁,这个方法 not 与同步请求一起工作(即当 xhr.open
设置为 false
)。
I'm trying to send a HTTP request from a Extension in which I need to change the User-Agent.
My code looks like this:
function getXMLHttpRequest(method, url, extraHeaders) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true)
for (var headerKey in extraHeaders) {
xhr.setRequestHeader(headerKey, extraHeaders[headerKey]);
}
return xhr;
}
//....
getXMLHttpRequest("POST", "....", { "User-Agent": "Blahblahblah" })
Then, I get an error "Refused to set unsafe header: UserAgent"
I need to change that because my Backend needs to have an special User-Agent, is it possible to do that from an extension?
I tried webRequest API, to change the header before sending the request, but it says it does not work with XMLHttpRequest made from extensions in order to prevent locking.
You can easily change the User-Agent header with the webRequest
API.
For sample code, see Associate a custom user agent to a specific Google Chrome page/tab.
Take the code from that answer, and change "main_frame", "sub_frame"
to "xmlhttprequest"
to modify network requests initiated via XMLHttpRequest
.
Obviously, to prevent deadlocks, this method does not work with synchronous requests ( i.e. when the third parameter of xhr.open
is set to false
).
这篇关于从Chrome扩展程序更改XMLHttpRequest中的User-Agent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!