Chrome(谷歌)插件开发 监听网站的异步请求

为什么要开发这样的一个插件:微信小程序用户反馈 不能知道那些问题是被回复了以及回复了什么内容,所以需要去监听这个网站的回复内容。由于它的客服系统获取聊天信息都是异步的,可以通过监听网站的异步请求 获取到参数、响应结果,用于处理这块的业务信息。

插件下载

谷歌插件学习监听网络请求-Javascript文档类资源-CSDN下载

业务流程 

 监听ajax请求的核心代码

main.js

;(function () {
  if ( typeof window.CustomEvent === "function" ) return false;
 
  function CustomEvent ( event, params ) {
      params = params || { bubbles: false, cancelable: false, detail: undefined };
      var evt = document.createEvent( 'CustomEvent' );
      evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
      return evt;
  }   
  CustomEvent.prototype = window.Event.prototype;   
  window.CustomEvent = CustomEvent;
})();
;(function () {
  function ajaxEventTrigger(event) {
      var ajaxEvent = new CustomEvent(event, 
        { 
          detail: {
                    readyState:this.readyState,
                    responseURL:this.responseURL,
                    status:this.status,
                    response:this.response,
                    orignUrl:this.orignUrl,
                    body:this.body,
                    method:this.method
                  } 
         });
      window.dispatchEvent(ajaxEvent);
  }
  
  var oldXHR = window.XMLHttpRequest;
 
  function newXHR() {
      var realXHR = new oldXHR();

      realXHR.addEventListener('abort', function () { ajaxEventTrigger.call(this, 'ajaxAbort'); }, false);
      realXHR.addEventListener('error', function () { ajaxEventTrigger.call(this, 'ajaxError'); }, false);
      realXHR.addEventListener('load', function () { ajaxEventTrigger.call(this, 'ajaxLoad'); }, false);
      realXHR.addEventListener('loadstart', function () { ajaxEventTrigger.call(this, 'ajaxLoadStart'); }, false);
      realXHR.addEventListener('progress', function () { ajaxEventTrigger.call(this, 'ajaxProgress'); }, false);
      realXHR.addEventListener('timeout', function () { ajaxEventTrigger.call(this, 'ajaxTimeout'); }, false);
      realXHR.addEventListener('loadend', function () { ajaxEventTrigger.call(this, 'ajaxLoadEnd'); }, false);
      realXHR.addEventListener('readystatechange', function() { ajaxEventTrigger.call(this, 'ajaxReadyStateChange'); }, false);

      let send = realXHR.send;
      realXHR.send = function(...arg){
          send.apply(realXHR,arg);
          realXHR.body = arg[0];
          ajaxEventTrigger.call(realXHR, 'ajaxSend');
      }

      let open = realXHR.open;
      realXHR.open = function(...arg){
          open.apply(realXHR,arg)
          realXHR.method = arg[0];
          realXHR.orignUrl = arg[1];
          realXHR.async = arg[2];
          ajaxEventTrigger.call(realXHR, 'ajaxOpen');
      }

      let setRequestHeader = realXHR.setRequestHeader;
      realXHR.requestHeader = {};
      realXHR.setRequestHeader = function(name, value){
          realXHR.requestHeader[name] = value;
          setRequestHeader.call(realXHR,name,value)
      }
      return realXHR;
  }
 
   window.XMLHttpRequest = newXHR;
})();

manifest.json

{
  "manifest_version": 3,

  "name": "采集助手",
  "description": "xxxxxx",
  "version": "1.0",

  "action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs",
    "activeTab",
    "storage",
    "webRequest"
  ],
  "host_permissions": [
    "*://*/*",
    "http://*/*",
    "https://*/*",
    "https://back.welife001.com/"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [    
    {
      "matches": ["https://xxxx/*"], //替换自己需要监听的网站地址   
      "js": ["auto.js","jquery-2.0.0.min.js"],		
      "run_at": "document_start"
    }
  ],
  "web_accessible_resources": [
    { 
      "resources": ["pageScripts/defaultSettings.js","pageScripts/main.js"],
      "matches": ["https://xxxx/*"] //替换自己需要监听的网站地址
    }
  ]
}

auto.js



// 在页面上插入代码

const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.runtime.getURL('pageScripts/main.js'));
document.documentElement.appendChild(script);

script.addEventListener('load', () => {
    // postMessage({type: 'ajaxInterceptor', to: 'pageScript', key: 'ajaxInterceptor_switchOn', value: true});
    // postMessage({type: 'ajaxInterceptor', to: 'pageScript', key: 'ajaxInterceptor_rules', value: ['action=get_room_msg']});
    const meta = document.createElement('meta');
    meta.setAttribute('http-equiv', 'Content-Security-Policy');
    meta.setAttribute('content', 'upgrade-insecure-requests');
    document.getElementsByTagName('head')[0].prepend(meta);
    console.log('jiazai')
});


//写自己的业务逻辑代码
window.addEventListener("ajaxReadyStateChange",function(e){
    let xhr = e.detail;
    if(xhr && xhr.readyState == 4 && xhr.status == 200){
        // xhr.getAllResponseHeaders()  响应头信息
        // xhr.requestHeader            请求头信息
        // xhr.responseURL              请求的地址
        // xhr.responseText             响应内容
        // xhr.orignUrl                 请求的原始参数地址
        // xhr.body                     post参数,(get参数在url上面)

        //判断请求分别是什么动作
        if(xhr.orignUrl.includes('get_room_info')){ //获取用户聊天室详情
            dealChatInfo(xhr.response)
        }else if(xhr.orignUrl.includes('get_room_msg')){ //获取用户聊天列表
            //解析请求的参数 用来判断是刷新请求还是 获取历史聊天
            let param  = JSON.parse(xhr.body)
            if(param.op == 0){//获取历史聊天
                dealChatResponse(xhr.response,param.op)
            }else if(param.op == 1){//刷新请求
                if(xhr.response.list.length>0){//有聊天内容 才去同步
                    dealChatResponse(xhr.response,param.op)
                }
            }

        }else if(xhr.orignUrl.includes('send_room_msg')){ //客服回复内容
            dealChatSend(xhr.response,xhr.body)
        }
        // console.log(xhr);
    }
});
/**
 * 同步聊天信息
 * @param {*} response 
 * @param {*} op 
 */
function dealChatResponse(response,op){
    // console.log('聊天列表',response)
    chrome.storage.local.get(['room_attr'], function(result) {
        if(result){
            let user_head_img = result.room_attr.user_head_img
            let list = response.list
            // console.log(user_head_img)
            $.ajax({
                url: "xxx",
                type: "post",
                data:{list:list,op:op,head_url:user_head_img},
                dataType: "json"
            }).done(function(msg) {
                console.log( '同步消息成功',msg)
            }).fail(function(jqXHR, textStatus) {
                console.log( '同步消息失败')
            });
        }
    });
    
}

/**
 * 获取聊天室详情,需要将客服的信息保存起来
 * @param {*} response 
 */
function dealChatInfo(response){
    // console.log('聊天室详情',response)
    //保存聊天室详情
    chrome.storage.local.set({'room_attr': response.room_attr}, function() {});
}
/**
 * 处理客服发送消息
 * @param {*} response 
 * @param {*} body 
 */
function dealChatSend(response,body){
    // console.log('发送消息',JSON.parse(body))
    let json_body = JSON.parse(body);
    chrome.storage.local.get(['room_attr'], function(result) {
        if(result){
            let extra_info = json_body.extra_info
            let msg_content = json_body.msg_content
            let user_head_img = result.room_attr.user_head_img
            let msg_type = json_body.msg_type
            $.ajax({
                url: "xxx",
                type: "post",
                data:{extra_info:extra_info,msg_content:msg_content,head_url:user_head_img,msg_type:msg_type},
                dataType: "json"
            }).done(function(msg) {
                console.log( '发送消息成功',msg)
            }).fail(function(jqXHR, textStatus) {
                console.log( '发送消息失败')
            });
        }
    });
}

参考

  • https://www.cnblogs.com/fbj333/p/15709444.html
  • https://blog.csdn.net/joy1793/article/details/109364821
  • https://blog.csdn.net/Nieyigo/article/details/116482585

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

古月_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值