每当看到不错的帖子想收藏、点赞或者关注作者时,总是会遇到下面的问题
看了下请求包,发现是每次请求都会带上csrf_token,但是因为token超时了所以操作失败。刷新页面后立即点赞等操作就能成功。作为一个懒癌不想每次都刷新,自然就想到写个油猴脚本在操作前先重新获取token,脚本不难,如下
讲下脚本为何这么写:
1.本来想用jQuery.ajax()来发包,结果发现返回包为空,对比下正常刷新页面的请求包,发现是"X-Requested-With: XMLHttpRequest"请求头导致的,所以改用XMLHttpRequest。
2.xmlhttp.open("GET", location.href, false)需要设置第三个参数为false,即同步请求,否则token还没来得及刷新,又会报token check error。
3.新添加的刷新token事件监听器在原监听器之后执行,所以需要调整监听器顺序,放在最前面。同时关注和点赞在侧边和底部都有,所以这两处都需要调整。
https://stackoverflow.com/a/8567149
http://www.robeesworld.com/blog/67/changing-the-order-of-the-jquery-event-queue
文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
/
/
=
=
UserScript
=
=
/
/
@name kanxue refresh token
/
/
@namespace http:
/
/
tampermonkey.net
/
/
/
@version
0.1
/
/
@description kanxue refresh token
/
/
@author You
/
/
@match https:
/
/
bbs.kanxue.com
/
*
/
/
@icon data:image
/
gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw
=
=
/
/
@grant none
/
/
=
=
/
UserScript
=
=
var jQuery
=
window.jQuery;
function RefreshToken(){
var csrftoken
=
jQuery(
'meta[name="csrf-token"]'
).attr(
'content'
);
var xmlhttp
=
new XMLHttpRequest();
xmlhttp.onreadystatechange
=
function() {
if
(xmlhttp.readyState
=
=
XMLHttpRequest.DONE) {
if
(xmlhttp.status
=
=
200
) {
var response
=
jQuery(xmlhttp.responseText);
var $csrfMeta
=
response.
filter
(
'meta[name="csrf-token"]'
);
var new_csrftoken
=
$csrfMeta.attr(
'content'
);
jQuery(
'meta[name="csrf-token"]'
).attr(
'content'
, new_csrftoken);
}
else
if
(xmlhttp.status
=
=
400
) {
alert(
'There was an error 400'
);
}
else
{
alert(
'something else other than 200 was returned'
);
}
}
};
xmlhttp.
open
(
"GET"
, location.href, false);
xmlhttp.send();
}
(function() {
'use strict'
;
var array
=
[
".favorite"
,
".thumb"
,
".follow_btn"
];
for
(var i
=
0
; i < array.length; i
+
+
){
jQuery(array[i]).on(
'click'
, function(event) {
RefreshToken();
})
for
(var j
=
0
; j < jQuery(array[i]).length; j
+
+
){
var eventList
=
jQuery._data(jQuery(array[i])[j],
"events"
);
eventList.click.unshift(eventList.click.pop());
}
}
})();
/
/
=
=
UserScript
=
=
/
/
@name kanxue refresh token
/
/
@namespace http:
/
/
tampermonkey.net
/
/
/
@version
0.1
/
/
@description kanxue refresh token
/
/
@author You
/
/
@match https:
/
/
bbs.kanxue.com
/
*
/
/
@icon data:image
/
gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw
=
=
/
/
@grant none
/
/
=
=
/
UserScript
=
=
var jQuery
=
window.jQuery;
function RefreshToken(){
var csrftoken
=
jQuery(
'meta[name="csrf-token"]'
).attr(
'content'
);
var xmlhttp
=
new XMLHttpRequest();
xmlhttp.onreadystatechange
=
function() {
if
(xmlhttp.readyState
=
=
XMLHttpRequest.DONE) {
if
(xmlhttp.status
=
=
200
) {
var response
=
jQuery(xmlhttp.responseText);
var $csrfMeta
=
response.
filter
(
'meta[name="csrf-token"]'
);
var new_csrftoken
=
$csrfMeta.attr(
'content'
);
jQuery(
'meta[name="csrf-token"]'
).attr(
'content'
, new_csrftoken);
}
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课