好友
阅读权限25
听众
最后登录1970-1-1
|
编写的原因:1 在浏览器中有时候跨页面通信很不方便
2 在https网站中,如果要和自己的http网站跨域通信,在注入脚本中是不允许的,但可以通过background.js 中转。(background.js中请求不受限制)
3 在注入脚本中定时刷新页面,如果页面加载失败代码不起作用。
4 在注入脚本中打开新窗口(window.open),浏览器默认会屏蔽。
解决以上问题,故此插件应运而生
background.js代码
[JavaScript] 纯文本查看 复制代码 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] 纯文本查看 复制代码 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"}});
*/
|
免费评分
-
查看全部评分
|