Chrome 扩展中 监听网页请求和响应

Chrome 扩展中 监听网页请求和响应

亲测有效

manifest.json 文件

{

  "permissions": [
    "tabs",
    "cookies",
    "storage",
    "activeTab",
    "scripting",
    "webRequest",
    "webRequestBlocking",
    ""
  ],
  "content_scripts": [
    {
      "matches": [
        ""
      ],
      "js": [
        "content.js"
      ]
    }
  ],
  "web_accessible_resources": [
    "injected.js"
  ],
}

injected.js

console.log("injected.js");

$(document).ajaxComplete(function (event, xhr, settings) {
    console.log(window.postMessage, event, xhr, settings);
    // 自行补充需要的数据
    window.postMessage({ type: "api-listener" }, '*');  // 将响应发送到 content.js
});

content.js


// 代码注入到宿主页面
var s = document.createElement('script');
s.src = chrome.runtime.getURL('injected.js');
console.log('引入js脚本', s);
s.onload = function () {
    this.remove();
};
document.getElementsByTagName('head')[0].appendChild(s);

window.addEventListener('message', function (e) {
	// 输出监听的请求内容
    console.log("message", e);
});

你可能感兴趣的:(chrome,javascript,前端)