|
发表于
2023-1-1 11:18:21
|
显示全部楼层
目的:想实现劫持一个json请求(请求A)。然后将拿到的请求(请求A)判断后,再发json请求B,将请求B的结果,修改到请求A,再将A返回。下方的代码无法实现这个运行。因为请求B的内容放到A的劫持函数中会变成一个promise对象。promise对象的then中无法赋值到外层。
- // ==UserScript==
- // [url=home.php?mod=space&uid=23356]@name[/url] 【Major】劫持并修改
- // @namespace https://bbs.tampermonkey.net.cn/
- // @version 0.1.2
- // @description try to take over the world!
- // @author You
- // [url=home.php?mod=space&uid=52134]@match[/url] http*://*/lists?cid=*
- // @match http*://*/show?id=*
- // @require https://scriptcat.org/lib/637/1.0.0/ajaxHooker.js
- // @grant GM_xmlhttpRequest
- // @grant unsafeWindow
- // @run-at document-start
- // ==/UserScript==
- // 在此处键入代码……
- unsafeWindow.GM_cookie = GM_cookie;
- unsafeWindow.GM_xmlhttpRequest = GM_xmlhttpRequest;
- let configf = {
- hookJson: function(){
- console.log('hook:','start')
- ajaxHooker.hook(request => {
- console.log('request.url:',request.url)
- console.log(request.data)
- console.log('request.method:',request.method)
- if (request.url === '/api/show' && request.method === 'POST') {
- console.log('hoolk:','sess')
- // request.data = val => {
- // const postData = JSON.parse(val);
- // console.log(postData);
- // return JSON.stringify(postData);
- // };
- request.response = res => {
- try{
- oldJson = JSON.parse(res.responseText);
- if(oldJson.is_see === false){
- // 这里返回的是一个 promise对象,怎样才能把值取出来,并修改到劫持中再返回???
- let mes = configf.awaitMessage();
- mes.then((getmes) => {
- console.log("result", getmes);
- oldJson.QQ = getmes.qq;
- oldJson.phone = getmes.phone;
- oldJson.wechat = getmes.wechat;
- oldJson.address = getmes.address;
- oldJson.is_see = true;
- console.log("result>>>>>", oldJson);
- res.responseText = JSON.stringify(oldJson);
- })
- };
- }catch (e){
- console.log('erro:',e)
- res.responseText
- };
- };
- };
- });
- },
- getmessage:function(){
- return new Promise(function (resolve, reject) {
- let url = "http://127.0.0.1:16999/ylyf/api/post"
- let id = configf.getUrlParams();
- console.log(id)
- id = id.id;
- GM_xmlhttpRequest({
- method: "POST",
- url: url,
- data:JSON.stringify({"id":id}),
- onload: function(res){
- if(res.status === 200){
- console.log(res.responseText)
- }else{
- console.log('send 数据失败'+'返回代码:'+String(res.status))
- };
- resolve(res.responseText)
- },
- onerror : function(err){
- console.log('send 数据遇到错误',err)
- reject();
- }
- });
- });
- },
- awaitMessage:async function(){
- res = await configf.getmessage();
- localStorage.message = res;
- return res
- },
- };
- (function(){
- configf.hookJson();
- })()
复制代码 |
|