吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3651|回复: 25
上一主题 下一主题
收起左侧

[其他原创] 分享一个自己写的浏览器插件通信代码

[复制链接]
跳转到指定楼层
楼主
Pwaerm 发表于 2021-11-29 09:24 回帖奖励
编写的原因:1 在浏览器中有时候跨页面通信很不方便
2 在https网站中,如果要和自己的http网站跨域通信,在注入脚本中是不允许的,但可以通过background.js  中转。(background.js中请求不受限制)
3 在注入脚本中定时刷新页面,如果页面加载失败代码不起作用。
4 在注入脚本中打开新窗口(window.open),浏览器默认会屏蔽。

解决以上问题,故此插件应运而生

background.js代码
[JavaScript] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
function httpRequest(params, successFun, errFun) {
  var _xhr = new XMLHttpRequest();
  var _type = (params.type || 'GET').toUpperCase();
  var _async = params.async || false;
  /*请求参数--post请求参数格式为:foo=bar&lorem=ipsum*/
  var _data = params.data || {};
  var _array = [];
  for (var _key in _data) {
    _array.push(_key + "=" + _data[_key]);
  }
  _data = _array.join("&");
  //console.log(_data);
  /*请求接收*/
  _xhr.onreadystatechange = function () {
    if (_xhr.readyState == 4) {
      if (_xhr.status == 200) {
        //console.log(_xhr.responseText);
        successFun(_xhr.responseText);
      } else {
        if (typeof errFun == "function") errFun();
      }
    } else {
 
    }
  }
  /*接口连接,先判断连接类型是post还是get*/
  if (_type == 'GET') {
    _xhr.open("GET", params.url + (_data ? "?" + _data : ""), _async);
    _xhr.send(null);
  } else if (_type == 'POST') {
    _xhr.open("POST", params.url, _async);
    //发送合适的请求头信息
    _xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    _xhr.send(_data);
  }
}
//--------去除注释---------
var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;
function commentReplace(match, multi, multiText, singlePrefix) {
  return singlePrefix || '';
}
function executeScript(_id, _url, _in = "box", _callBack) {
  httpRequest({ type: "GET", async: true, url: _url }, function (_code) {
    _code = _code.replace(commentRegExp, commentReplace);
    //console.log(_code);
    //注入到沙箱
    if (_in == "box" || _in == "all") {
      chrome.tabs.executeScript(_id, { code: "var pageName='boxPage';" + _code });
    }
    //注入到用户脚本
    if (_in == "user" || _in == "all") {
      _code = encodeURIComponent(_code);
      var _script = "var s=document.createElement(\"script\");";
      _script += "s.innerHTML='var pageName=\"userPage\";eval(decodeURIComponent(window.atob(\"" + window.btoa(_code) + "\")))';";
      _script += "document.getElementsByTagName('HEAD')[0].appendChild(s);";
      chrome.tabs.executeScript(_id, { code: _script });
    }
    chrome.browserAction.setBadgeText({ tabId: _id, text: _in });
    if (typeof _callBack == "function") {
      _callBack();
    }
  });
}
function updateOtherTabs(_tab) {
  chrome.tabs.remove(_tab.id);
  chrome.tabs.getAllInWindow(null, function (tabs) {
    tabs.forEach(function (tab) {
      if (tab.url.indexOf("http") != -1) {
        chrome.tabs.update(tab.id, { selected: true, url: tab.url });
      }
    });
  })
}
//-------------------------------------------------
//接收消息(数据,发出事件的Tab,回调函数)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log("background->request.type:" + request.type);
  //PagePopup页面勾选动作
  if (request.type == "popupChecked") {
    if (request.id == "xxqg") {
      checkFastTotal();
    }
    sendResponse("菜单勾选动作");
    return;
  }
  //刷新当前页
  if (request.type == 'reload') {
    if (sender.tab) {
      chrome.tabs.update(sender.tab.id, { selected: true, url: sender.tab.url });
    }
    sendResponse("刷新当前页成功");
    return;
  }
  //刷新主页
  if (request.type == 'reloadHome') {
    var _key = "xuexi.cn";
    if (request.data && request.data.homeKey) {
      _key = request.data.homeKey;
    }
    if (request.data && request.data.homeUrl) {
      _homeUrl = request.data.homeUrl;
    }
    chrome.tabs.getAllInWindow(null, function (tabs) {
      var _isUpdate = false;
      tabs.forEach(function (tab) {
        //刷新带有关键字的标签,如果已经刷新了一个,其它的就关闭
        if (tab.url.indexOf(_key) != -1) {
          if (!_isUpdate) {
            _isUpdate = true;
            chrome.tabs.update(tab.id, { selected: true, url: tab.url });
          } else {
            chrome.tabs.remove(tab.id);
          }
        }
      });
      if (!_isUpdate) {
        chrome.tabs.create({ url: _homeUrl, selected: true }, function (tab) {
          //chrome.tabs.executeScript(tab.id, { file: 'src/contentScript2' });
        });
      }
      tabs.forEach(function (tab) {
        if (tab.url.indexOf(_key) == -1) {
          chrome.tabs.remove(tab.id);
        }
      });
    });
    sendResponse("刷新主页成功");
    return;
  }
  //打开一个新页面
  if (request.type == "openUrl" || request.type == "openWindow" || request.type == "createTab") {
    chrome.tabs.create({ url: request.data.url, selected: request.data.selected ? true : false });
    return;
  }
  //激活当前标签
  if (request.type == "activityTab") {
    if (!sender.tab.active) {
      chrome.tabs.update(sender.tab.id, { selected: true });
      sendResponse("页面激活成功");
    } else {
      sendResponse("当前页已处于激活状态");
    }
    return;
  }
  //获取chrome对象
  if (request.type == 'getChrome') {
    sendResponse(chrome);
    return;
  }
  //获取标签总量
  if (request.type == 'getTabNums') {
    sendResponse(tabsInfo.length);
    return;
  }
  //获取标签信息
  if (request.type == 'getTabsInfo') {
    sendResponse(tabsInfo);
    return;
  }
  //刷新其它标签页
  if (request.type == 'updateOtherTabs') {
    updateOtherTabs(sender.tab);
    sendResponse("刷新其它页面成功");
    return;
  }
  //关闭其它标签页
  if (request.type == 'closeOtherTabs') {
    chrome.tabs.getAllInWindow(null, function (tabs) {
      tabs.forEach(function (tab) {
        if (tab.id != sender.tab.id) {
          chrome.tabs.remove(tab.id);
        }
      });
    });
    sendResponse("关闭其它页面成功");
    return;
  }
  //关闭或者保留指定标签页
  if (request.type == 'closeTabsFromKey') {
    var _keys = request.data;
    chrome.tabs.query({}, function (tabs) {
      tabs.forEach(function (tab) {
        if (_keys.keepKey) {
          if (tab.id == _keys.keepKey || tab.url.indexOf(_keys.keepKey) != -1) {
            return;
          }
        }
        if (_keys.closeKey) {
          if (tab.id == _keys.colseKey || tab.url.indexOf(_keys.closeKey) != -1) {
            chrome.tabs.remove(tab.id);
          }
        }
      });
    });
    sendResponse("关闭指定标签成功!");
    return;
  }
  //读取网络数据
  if (request.type == "getDataFromUrl") {
    var _data = "读取网络数据";
    httpRequest(request.data, function (data) {
      //console.log("callBack:" + data, sendResponse);
      _data = data;
    }, function () {
      console.log('网络错误');
      _data = "网络错误";
    });
    sendResponse(_data);
    return;
  };
  //倒计时刷新
  if (request.type == 'reloadTime') {
    if (sender.tab) {
      startTime(sender.tab, request.data.time);
    }
    sendResponse("设置刷新倒计时成功");
    return;
  }
  //停止倒计时刷新
  //关闭
  if (request.type == 'closeWindow') {
    if (sender.tab) {
      chrome.tabs.remove(sender.tab.id);
    }
    sendResponse("关闭页面成功");
    return;
  }
  //插入JS,in参数为 box  或者 page
  if (request.type == 'executeScript') {
    //console.log("script:"+request.data.url);     
    executeScript(sender.tab.id, request.data.url, request.data.in);
    sendResponse("注入成功");
    return;
  }
  //获取localStorage
  if (request.type == "getLocalStorage") {
    if (localStorage[request.data.key]) {
      sendResponse(localStorage[request.data.key]);
    } else {
      sendResponse("0");
    }
    return;
  }
});
//------------------------
var tabsInfo = [];
var serverPath = "http://127.0.0.1/";
var timers = {};
function stopTime(id) {
  chrome.tabs.query({}, function (tabs) {
    tabsInfo = tabs;
  });
  if (timers[id] != undefined) {
    clearInterval(timers[id]);
    delete timers[id];
  }
}
function startTime(tab, _time) {
  chrome.tabs.query({}, function (tabs) {
    tabsInfo = tabs;
  });
  if (_time == undefined) {
    return;
  }
  stopTime(tab.id);
  //console.log("startTime:"+tab.id);  
  timers[tab.id] = setInterval(function () {
    chrome.browserAction.setBadgeText({ tabId: tab.id, text: String(_time) });
    _time--;
    if (_time <= 0) {
      stopTime(tab.id);
      chrome.tabs.update(tab.id, { url: tab.url });
    }
  }, 1000);
}
chrome.tabs.onRemoved.addListener(stopTime);
chrome.tabs.onCreated.addListener(startTime);
//---------------------------------
function onTabUpdate(tabId, changeInfo, tab) {
  console.log("onTabUpdate:", changeInfo.status);
  if (changeInfo.status == "loading") {
    //所有页面5分钟后刷新,加载成功则停止
    startTime(tab, 300);
    return;
  }
  if (changeInfo.status == "complete") {
    //停止插件自己设定的刷新
    stopTime(tab.id);
    //-----
    if (!tab.url.match(/^http/)) { return; }
    //出错的标签倒计时刷新
    try {
      if (typeof tab.title == "string") {
        console.log(tab.title);
        if (tab.title.indexOf("chrome://errorpage/?errorcode") != -1 || tab.title.indexOf("Not Found") != -1) {
          startTime(tab, 10);
        }
        if (tab.title.indexOf("404") != -1) {
          //updateOtherTabs(tab);
        }
      }
    } catch (e) {
 
    }
    //加载通信接口 
    executeScript(tabId, 'http://www.flash023.cn/js/message.js?r' + Math.random(), "all", function () {
 
      if (tab.url.indexOf("xxxxx") != -1) {
//注入远程代码是方便修改
        executeScript(tabId, '此处注入对应网站的代码远程地址.js?r' + Math.random(), "user");
        return;
      }
    });
  }
}
chrome.tabs.onUpdated.addListener(onTabUpdate);



通信接口代码 http://www.flash023.cn/js/message.js

[Asm] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
if (!window.hasEventListener) {
  window.hasEventListener = {};
}
function getFunKey() {
  var _keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var _key = "";
  for (var _i = 0; _i < 18; _i++) {
    _key += _keys.charAt(Math.floor(Math.random() * _keys.length));
  }
  return _key;
}
if (typeof pageName != "undefined" && pageName == "boxPage") {
  //插件沙箱环境
  if (!window.hasEventListener["message"]) {
    window.hasEventListener["message"] = true;
    window.addEventListener("message", function (event) {
      if (event.data.type == "chrome.runtime.sendMessage") {
        chrome.runtime.sendMessage(event.data.data, function (_data) {
          window.postMessage({ type: "chrome.runtime.sendMessage_BACK", callBackKey: event.data.callBackKey, data: _data }, location.href);
        });
      }
    });
  }
  //--------------------
  //使用window发出自定义事件
  if (!window.hasEventListener["SEND_MESSAGE"]) {
    console.log("SEND_MESSAGE_INIT");
    window.hasEventListener["SEND_MESSAGE"] = true;
    window.addEventListener("SEND_MESSAGE", function (e) {
      var _ed = e.detail;
      //console.log("SEND的数据:", _ed);
      if (_ed) {
        //console.log("sendMessage-->type:" + _ed.type);
        chrome.runtime.sendMessage(_ed, function (_data) {
          if (typeof _data == "object") {
            _data.funKey = _ed.funKey;
          } else {
            var _o;
            try {
              _o = JSON.parse(_data);
            } catch (e) {
              _o = _data;
            }
            _data = { funKey: _ed.funKey, data: _o };
          }
          //console.log("background回调", _data);
          var e = new CustomEvent("SEND_MESSAGE_BACK", { detail: _data });
          window.dispatchEvent(e);
        });
      }
    });
  }
}
if (typeof pageName != "undefined" && pageName == "userPage") {
  //利用window.postMessage传递(可跨域)
  if (!window.hasEventListener["message"]) {
    window.hasEventListener["message"] = true;
    window.addEventListener("message", function (event) {
      if (event.data.type == "chrome.runtime.sendMessage_BACK") {
        if (typeof window[event.data.callBackKey] == "function") {
          window[event.data.callBackKey](event.data.data);
          window[event.data.callBackKey] = null;
        }
      }
    });
    window.chromeMessage = function (_data, _callBack) {
      var _callBackKey = getFunKey();
      window[_callBackKey] = _callBack;
      window.postMessage({ type: "chrome.runtime.sendMessage", callBackKey: _callBackKey, data: _data }, location.href);
    }
  }
  //用户页面注入
  console.log("SEND_MESSAGE_BACK_INIT");
  window.sendMessage = function (_data, _callBack) {
    if (!window.hasEventListener["SEND_MESSAGE_BACK"]) {
      window.hasEventListener["SEND_MESSAGE_BACK"] = true;
      window.addEventListener("SEND_MESSAGE_BACK", function (_e) {
        //console.log(_e.detail);
        var _ed = _e.detail;
        if (typeof window[_ed.funKey] == "function") {
          window[_ed.funKey](_ed);
          window[_ed.funKey] = null;
        }
      });
    }
    _data.funKey = getFunKey();
    window[_data.funKey] = _callBack;
    //15秒超时
    //setTimeout(function (_funKey) { window[_funKey] = null; console.log("超时,清除函数!") }, 15 * 1000, _data.funKey);
    var e = new CustomEvent("SEND_MESSAGE", { detail: _data });
    window.dispatchEvent(e);
  }
}
 
/*
//获取标签总量
window.sendMessage ({type:"getTabNums"});
//获取标签信息
window.sendMessage({ type: "getTabsInfo" }, function (data) {console.log("标签信息对象:", data);});
//刷新当前页
window.sendMessage ({type:"reload"});
//激活当前页
window.sendMessage({ type: "activityTab" }, function (data) {console.log(data)});
//关闭当前页,并刷新其它页面
window.sendMessage ({type:"updateOtherTabs"});
//刷新主页
window.sendMessage ({type:"reloadHome",data:{homeKey:"保留的主页关键字",homeUrl:"当关键字主页一个也没有时,打开的地址"}});
//关闭其它标签
window.sendMessage ({type:"closeOtherTabs"});
//倒计时刷新
window.sendMessage ({type:"reloadTime", data:{time:"刷新倒计时秒灵敏"}});
//关闭当前页
window.sendMessage ({type:"closeWindow"});
//关闭指定标签页(关键字)
window.sendMessage({type:"closeTabsFromKey", data:{keepKey:"保留关键字",closeKey:"关闭关键字"}});
//打开一个新的标签页
window.sendMessage({type:"createTab", data:{url:"要打开的链接",selected:"是否激活"}});
// 获取网络数据
window.sendMessage({ type: "getDataFromUrl", data: { url: "Pwaerm/proxy.php", type: "POST", data: { type: "getFastTotal" } } }, function (data) {
  console.log("注入脚本收到:", data);
});
//注入JS
window.sendMessage ({type:"executeScript",data:{url:"JS地址",in:"注入到box 还是user"}});
*/

免费评分

参与人数 11威望 +1 吾爱币 +31 热心值 +9 收起 理由
笙若 + 1 + 1 谢谢@Thanks!
jingtaozhushou + 1 + 1 谢谢@Thanks!
Liml8888 + 1 我很赞同!
xspapdc + 1 + 1 学习一下,太牛了。
苏紫方璇 + 1 + 20 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
124544802 + 1 鼓励转贴优秀软件安全工具和文档!
lxhyjr + 1 + 1 谢谢@Thanks!
十三2020 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
chizhuba1 + 1 + 1 谢谢@Thanks!
Reer + 1 + 1 热心回复!
何故 + 3 + 1 用心讨论,共获提升!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

推荐
 楼主| Pwaerm 发表于 2021-11-29 09:56 |楼主
涛之雨 发表于 2021-11-29 09:42
如果方便的话可以把打包后的zip发出来(福利区,然后把帖子链接插入本帖)
有很多人不懂得如何构建插件

crx.rar (38.74 KB, 下载次数: 52)   这是源文件,在浏览器中可以直接“加载已解压的扩展”  也可以用浏览器打包分享


谢谢提醒
推荐
hqhlwz 发表于 2021-11-29 18:56
涛之雨 发表于 2021-11-29 09:42
如果方便的话可以把打包后的zip发出来(福利区,然后把帖子链接插入本帖)
有很多人不懂得如何构建插件

好 大神 可以更新一下你的Checker Plus for Gmail版本  旧版已经不能删除邮件了
3#
涛之雨 发表于 2021-11-29 09:42
本帖最后由 涛之雨 于 2021-11-29 09:43 编辑

如果方便的话可以把打包后的zip发出来(福利区,然后把帖子链接插入本帖)
有很多人不懂得如何构建插件
4#
xtkj 发表于 2021-11-29 09:56
学习了。谢谢。
5#
soohai 发表于 2021-11-29 10:11
支持一下
6#
chizhuba1 发表于 2021-11-29 10:12
学习了,不是很懂。谢谢分享
7#
orb001 发表于 2021-11-29 10:13
我是来学习顺带膜拜大佬的。
8#
DayBreak 发表于 2021-11-29 10:28
感谢楼主分享,我觉得 ActiveMQ、RabbitMQ、ZeroMQ、Kafka、MetaMQ、RocketMQ 这些可能会好一点
9#
kennie611 发表于 2021-11-29 10:29

学习了,不是很懂。谢谢分享
10#
风入白袍 发表于 2021-11-29 10:41
&#128002;&#127866;
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-5-17 22:27

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表