编写Chrome插件将googleapis替换为国内可访问的CDN

编写Chrome插件将googleapis替换为国内可访问的CDN

由于公司不能安装梯子,所以不能访问谷歌商店,平时频繁地要访问国外的AngularJS网站,比如AgGrid,AngularJS Material,AngularJS官网等,很多用了Google的CDN源,页面就无法正常加载。

一开始的思路是改host文件,但是我们没有Google CDN的证书,会造成证书错误。

参考并优化了:https://github.com/justjavac/ReplaceGoogleCDN ,动手写了一个Chrome插件,对所有特定请求重定向,解决痛点!

新建2个文件,放在同目录下。

manifest.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "googleapis replacer",
"version": "0.1",
"manifest_version": 2,
"description": "googleapis replacer",
"background": {
"scripts": [
"main.js"
]
},
"permissions": [
"webRequest",
"webRequestBlocking",
"<all_urls>"
]
}
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var rules = [
{ "s": "ajax.googleapis.com", "t": "ajax.loli.net" },
{ "s": "fonts.googleapis.com", "t": "fonts.loli.net" },
];

chrome.webRequest.onBeforeRequest.addListener(
function (request) {
var redirectUrl;
var requestURL = request.url;

for (var i in rules) {
if (requestURL.indexOf(rules[i].s)) {
redirectUrl = requestURL.replace(rules[i].s, rules[i].t);
return { redirectUrl: redirectUrl };
}
}
},
{
urls: [
"*://ajax.googleapis.com/*",
"*://themes.googleusercontent.com/*"
]
},
["blocking"]
);
  1. 打开Chrome,输入: chrome://extensions/
  2. 勾选Developer Mode
  3. 选择Load unpacked extension…然后定位到代码文件夹,确定

测试:尝试访问 https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.js
拓展:可以在rules中添加更多自定义的规则。


封面来源, Cover source: https://wallpapertag.com/google-chrome-wallpaper-background

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×