Skip to content

Commit c5ffb78

Browse files
author
xiananliu
committed
大修改
1 parent 669babe commit c5ffb78

20 files changed

+790
-47
lines changed

demo/_locales/en/messages.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"pluginDesc": {"message": "A simple chrome extension demo"},
3+
"helloWorld": {"message": "Hello World!"}
4+
}

demo/_locales/zh_CN/messages.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"pluginDesc": {"message": "一个简单的Chrome插件demo"},
3+
"helloWorld": {"message": "你好啊,世界!"}
4+
}

demo/background.html

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>背景页</title>
5+
<meta charset="utf-8"/>
6+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7+
<style>
8+
html,body{height: 100%;font-size: 16px;}
9+
body{font-family: 'Microsoft Yahei';margin:0;padding:0;}
10+
.container {
11+
width: 1024px;
12+
margin: 0 auto;
13+
}
14+
</style>
15+
</head>
16+
<body>
17+
<div class="container">
18+
<h1>这是背景页</h1>
19+
<div>
20+
<a href="#" id="test_cors">跨域演示</a>
21+
</div>
22+
</div>
23+
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
24+
<script type="text/javascript" src="js/background.js"></script>
25+
</body>
26+
</html>

demo/css/custom.css

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
.chrome-plugin-demo-panel {
2+
position: fixed;
3+
right: 0;
4+
bottom: 10px;
5+
background: #3385ff;
6+
padding: 10px;
7+
box-shadow: 0px 0px 10px #002761;
8+
border-radius: 3px;
9+
color: white;
10+
}
11+
.chrome-plugin-demo-panel a{
12+
color: white;
13+
text-decoration: none;
14+
font-size: 16px;
15+
}
16+
.chrome-plugin-demo-panel a:hover{
17+
text-decoration: underline;
18+
color: #ffee08;
19+
}
20+
.chrome-plugin-simple-tip {
21+
position: fixed;
22+
left: 20px;
23+
padding: 16px 10px;
24+
top: 30px;
25+
color: white;
26+
min-width: 150px;
27+
max-width: 700px;
28+
border-radius: 3px;
29+
text-align: center;
30+
font-size: 16px;
31+
background: #70a800;
32+
background-image: linear-gradient(to bottom, #95cc2a, #70a800);
33+
box-shadow: 0 0 3px rgba(0, 0, 0, .2);
34+
transition: top .4s;
35+
}
36+
.animated {
37+
-webkit-animation-duration: .5s;
38+
animation-duration: .5s;
39+
-webkit-animation-fill-mode: both;
40+
animation-fill-mode: both
41+
}
42+
@-webkit-keyframes slideInLeft {
43+
0% {
44+
-webkit-transform: translate3d(-100%,0,0);
45+
transform: translate3d(-100%,0,0);
46+
visibility: visible
47+
}
48+
49+
100% {
50+
-webkit-transform: translate3d(0,0,0);
51+
transform: translate3d(0,0,0)
52+
}
53+
}
54+
55+
@keyframes slideInLeft {
56+
0% {
57+
-webkit-transform: translate3d(-100%,0,0);
58+
transform: translate3d(-100%,0,0);
59+
visibility: visible
60+
}
61+
62+
100% {
63+
-webkit-transform: translate3d(0,0,0);
64+
transform: translate3d(0,0,0)
65+
}
66+
}
67+
68+
.slideInLeft {
69+
-webkit-animation-name: slideInLeft;
70+
animation-name: slideInLeft
71+
}

demo/img/sds.png

58.2 KB
Loading

demo/js/background.js

Lines changed: 102 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,11 @@ chrome.contextMenus.create({
1919
chrome.tabs.create({url: 'https://www.baidu.com/s?ie=utf-8&wd=' + encodeURI(params.selectionText)});
2020
}
2121
});
22-
chrome.contextMenus.create({
23-
title: "获取当前页面tabId",
24-
onclick: function() {
25-
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
26-
{
27-
alert('当前tabId:' + (tabs.length ? tabs[0].id : '未知'));
28-
});
29-
}
30-
});
31-
3222

3323

3424

3525
//-------------------- badge演示 ------------------------//
36-
(function()
26+
/*(function()
3727
{
3828
var showBadge = false;
3929
var menuId = chrome.contextMenus.create({
@@ -56,6 +46,106 @@ chrome.contextMenus.create({
5646
showBadge = !showBadge;
5747
}
5848
});
59-
})();
49+
})();*/
50+
51+
// 监听来自content-script的消息
52+
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
53+
{
54+
console.log('收到来自content-script的消息:');
55+
console.log(request, sender, sendResponse);
56+
sendResponse('我是后台,我已收到你的消息:' + JSON.stringify(request));
57+
});
58+
59+
$('#test_cors').click((e) => {
60+
$.get('https://www.baidu.com', function(html){
61+
console.log( html);
62+
alert('跨域调用成功!');
63+
});
64+
});
65+
66+
// 获取当前选项卡ID
67+
function getCurrentTabId(callback)
68+
{
69+
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
70+
{
71+
if(callback) callback(tabs.length ? tabs[0].id: null);
72+
});
73+
}
74+
75+
// 当前标签打开某个链接
76+
function openUrlCurrentTab(url)
77+
{
78+
getCurrentTabId(tabId => {
79+
chrome.tabs.update(tabId, {url: url});
80+
})
81+
}
82+
83+
// 新标签打开某个链接
84+
function openUrlNewTab(url)
85+
{
86+
chrome.tabs.create({url: url});
87+
}
88+
89+
// omnibox 演示
90+
chrome.omnibox.onInputChanged.addListener((text, suggest) => {
91+
console.log('inputChanged: ' + text);
92+
if(!text) return;
93+
if(text == '美女') {
94+
suggest([
95+
{content: '中国' + text, description: '你要找“中国美女”吗?'},
96+
{content: '日本' + text, description: '你要找“日本美女”吗?'},
97+
{content: '泰国' + text, description: '你要找“泰国美女或人妖”吗?'},
98+
{content: '韩国' + text, description: '你要找“韩国美女”吗?'}
99+
]);
100+
}
101+
else if(text == '微博') {
102+
suggest([
103+
{content: '新浪' + text, description: '新浪' + text},
104+
{content: '腾讯' + text, description: '腾讯' + text},
105+
{content: '搜狐' + text, description: '搜索' + text},
106+
]);
107+
}
108+
else {
109+
suggest([
110+
{content: '百度搜索 ' + text, description: '百度搜索 ' + text},
111+
{content: '谷歌搜索 ' + text, description: '谷歌搜索 ' + text},
112+
]);
113+
}
114+
});
60115

116+
// 当用户接收关键字建议时触发
117+
chrome.omnibox.onInputEntered.addListener((text) => {
118+
console.log('inputEntered: ' + text);
119+
if(!text) return;
120+
var href = '';
121+
if(text.endsWith('美女')) href = 'http://image.baidu.com/search/index?tn=baiduimage&ie=utf-8&word=' + text;
122+
else if(text.startsWith('百度搜索')) href = 'https://www.baidu.com/s?ie=UTF-8&wd=' + text.replace('百度搜索 ', '');
123+
else if(text.startsWith('谷歌搜索')) href = 'https://www.google.com.tw/search?q=' + text.replace('谷歌搜索 ', '');
124+
else href = 'https://www.baidu.com/s?ie=UTF-8&wd=' + text;
125+
openUrlCurrentTab(href);
126+
});
127+
128+
// 预留一个方法给popup调用
129+
function testBackground() {
130+
alert('你好,我是background!');
131+
}
61132

133+
// 是否显示图片
134+
var showImage;
135+
chrome.storage.sync.get({showImage: true}, function(items) {
136+
showImage = items.showImage;
137+
});
138+
// web请求监听,最后一个参数表示阻塞式,需单独声明权限:webRequestBlocking
139+
chrome.webRequest.onBeforeRequest.addListener(details => {
140+
if(!showImage && details.type == 'image') return {cancel: true};
141+
// 简单的音视频检测
142+
// 大部分网站视频的type并不是media,且视频做了防下载处理,所以这里仅仅是为了演示效果,无实际意义
143+
if(details.type == 'media') {
144+
chrome.notifications.create(null, {
145+
type: 'basic',
146+
iconUrl: 'img/icon.png',
147+
title: '检测到音视频',
148+
message: '音视频地址:' + details.url,
149+
});
150+
}
151+
}, {urls: ["<all_urls>"]}, ["blocking"]);

demo/js/content-script.js

Lines changed: 119 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
// 注意,必须设置了run_at=document_start 此段代码才会生效
44
document.addEventListener('DOMContentLoaded', function()
55
{
6+
// 注入自定义JS
7+
injectCustomJs();
68
// 给谷歌搜索结果的超链接增加 _target="blank"
79
if(location.host == 'www.google.com.tw')
810
{
@@ -17,17 +19,17 @@ document.addEventListener('DOMContentLoaded', function()
1719
{
1820
function fuckBaiduAD()
1921
{
22+
if(document.getElementById('my_custom_css')) return;
2023
var temp = document.createElement('style');
2124
temp.id = 'my_custom_css';
2225
(document.head || document.body).appendChild(temp);
2326
var css = `
2427
/* 移除百度右侧广告 */
2528
#content_right{display:none;}
26-
[data-click] [data-tuiguang]{display:none;}
2729
/* 覆盖整个屏幕的相关推荐 */
2830
.rrecom-btn-parent{display:none;}'
2931
/* 难看的按钮 */
30-
.result-op{display:none !important;}`;
32+
.result-op.xpath-log{display:none !important;}`;
3133
temp.innerHTML = css;
3234
console.log('已注入自定义CSS!');
3335
// 屏蔽百度推广信息
@@ -40,6 +42,121 @@ document.addEventListener('DOMContentLoaded', function()
4042
});
4143
}
4244
fuckBaiduAD();
45+
initCustomPanel();
46+
initCustomEventListen();
4347
}
4448
});
4549

50+
function initCustomPanel()
51+
{
52+
var panel = document.createElement('div');
53+
panel.className = 'chrome-plugin-demo-panel';
54+
panel.innerHTML = `
55+
<h2>injected-script操作content-script演示区:</h2>
56+
<div class="btn-area">
57+
<a href="javascript:sendMessageToContentScriptByPostMessage('你好,我是普通页面!')">通过postMessage发送消息给content-script</a><br>
58+
<a href="javascript:sendMessageToContentScriptByEvent('你好啊!我是通过DOM事件发送的消息!')">通过DOM事件发送消息给content-script</a><br>
59+
<a href="javascript:invokeContentScript('sendMessageToBackground()')">发送消息到后台或者popup</a><br>
60+
</div>
61+
<div id="my_custom_log">
62+
</div>
63+
`;
64+
document.body.appendChild(panel);
65+
}
66+
67+
// 向页面注入JS
68+
function injectCustomJs(jsPath)
69+
{
70+
jsPath = jsPath || 'js/inject.js';
71+
var temp = document.createElement('script');
72+
temp.setAttribute('type', 'text/javascript');
73+
// 获得的地址类似:chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
74+
temp.src = chrome.extension.getURL(jsPath);
75+
temp.onload = function()
76+
{
77+
// 放在页面不好看,执行完后移除掉
78+
this.parentNode.removeChild(this);
79+
};
80+
document.head.appendChild(temp);
81+
}
82+
83+
// 接收来自后台的消息
84+
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
85+
{
86+
console.log('收到来自 ' + (sender.tab ? "content-script(" + sender.tab.url + ")" : "popup或者background") + ' 的消息:', request);
87+
if(request.cmd == 'update_font_size') {
88+
var ele = document.createElement('style');
89+
ele.innerHTML = `* {font-size: ${request.size}px !important;}`;
90+
document.head.appendChild(ele);
91+
}
92+
else {
93+
tip(JSON.stringify(request));
94+
sendResponse('我收到你的消息了:'+JSON.stringify(request));
95+
}
96+
});
97+
98+
// 主动发送消息给后台
99+
// 要演示此功能,请打开控制台主动执行sendMessageToBackground()
100+
function sendMessageToBackground(message) {
101+
chrome.runtime.sendMessage({greeting: message || '你好,我是content-script呀,我主动发消息给后台!'}, function(response) {
102+
tip('收到来自后台的回复:' + response);
103+
});
104+
}
105+
106+
// 监听长连接
107+
chrome.runtime.onConnect.addListener(function(port) {
108+
console.log(port);
109+
if(port.name == 'test-connect') {
110+
port.onMessage.addListener(function(msg) {
111+
console.log('收到长连接消息:', msg);
112+
tip('收到长连接消息:' + JSON.stringify(msg));
113+
if(msg.question == '你是谁啊?') port.postMessage({answer: '我是你爸!'});
114+
});
115+
}
116+
});
117+
118+
window.addEventListener("message", function(e)
119+
{
120+
console.log('收到消息:', e.data);
121+
if(e.data && e.data.cmd == 'invoke') {
122+
eval('('+e.data.code+')');
123+
}
124+
else if(e.data && e.data.cmd == 'message') {
125+
tip(e.data.data);
126+
}
127+
}, false);
128+
129+
130+
function initCustomEventListen() {
131+
var hiddenDiv = document.getElementById('myCustomEventDiv');
132+
if(!hiddenDiv) {
133+
hiddenDiv = document.createElement('div');
134+
hiddenDiv.style.display = 'none';
135+
hiddenDiv.id = 'myCustomEventDiv';
136+
document.body.appendChild(hiddenDiv);
137+
}
138+
hiddenDiv.addEventListener('myCustomEvent', function() {
139+
var eventData = document.getElementById('myCustomEventDiv').innerText;
140+
tip('收到自定义事件:' + eventData);
141+
});
142+
}
143+
144+
var tipCount = 0;
145+
// 简单的消息通知
146+
function tip(info) {
147+
info = info || '';
148+
var ele = document.createElement('div');
149+
ele.className = 'chrome-plugin-simple-tip slideInLeft';
150+
ele.style.top = tipCount * 70 + 20 + 'px';
151+
ele.innerHTML = `<div>${info}</div>`;
152+
document.body.appendChild(ele);
153+
ele.classList.add('animated');
154+
tipCount++;
155+
setTimeout(() => {
156+
ele.style.top = '-100px';
157+
setTimeout(() => {
158+
ele.remove();
159+
tipCount--;
160+
}, 400);
161+
}, 3000);
162+
}

0 commit comments

Comments
 (0)