使用Tampermonkey/Greasemonkey调用PyLoad API认证时Cookie缺失问题
我来帮你捋一捋这个问题的核心和解决办法:
首先检查请求是否启用了凭证携带
油猴脚本里的XMLHttpRequest或fetch请求,默认不会自动携带和接收Cookie(尤其是跨域场景)。你需要手动开启凭证支持:- 用XMLHttpRequest的话,一定要加上
xhr.withCredentials = true:const xhr = new XMLHttpRequest(); xhr.open('POST', '你的PyLoad API登录地址', true); xhr.withCredentials = true; // 这行是关键! xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { console.log("响应头:", xhr.getAllResponseHeaders()); console.log("响应内容:", xhr.responseText); }; xhr.send(JSON.stringify({username: '你的账号', password: '你的密码'})); - 如果用fetch API,要设置
credentials: 'include':fetch('你的PyLoad API登录地址', { method: 'POST', credentials: 'include', // 关键配置 headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username: '你的账号', password: '你的密码'}) }) .then(res => { console.log("响应头:", [...res.headers.entries()]); return res.text(); }) .then(data => console.log("响应内容:", data));
- 用XMLHttpRequest的话,一定要加上
确认脚本的跨域权限
如果PyLoad API的地址和你运行脚本的页面不同域,必须在脚本开头的元数据里加上@connect指令,比如:// ==UserScript== // @name PyLoad API 登录脚本 // @namespace http://tampermonkey.net/ // @version 0.1 // @description 调用PyLoad API登录 // @author You // @match *://你运行脚本的页面地址/* // @connect your-pyload-domain.com // 这里填PyLoad的域名 // @grant none // ==/UserScript==没有这个权限的话,浏览器会拦截跨域请求的Cookie传递。
关于Cookie的HttpOnly属性
如果PyLoad设置的Cookie带有HttpOnly标记,那么JavaScript(包括油猴脚本)是无法直接读取这个Cookie的,但只要你开启了上面的凭证配置,浏览器会在后续的API请求中自动携带这个Cookie,不影响正常调用。你在Firefox控制台能看到Cookie,可能是因为控制台能访问所有Cookie,而脚本只能访问非HttpOnly的。
你现在的情况是登录返回true说明API已经认可了你的登录请求,但因为脚本没配置凭证携带,所以响应里的Cookie没被浏览器关联到脚本的请求环境,导致后续请求也无法带上Cookie,而且脚本也看不到响应头里的Cookie信息。按照上面的配置调整后应该就能解决啦。
内容的提问来源于stack exchange,提问作者yoshiki




