Skip to content

Instantly share code, notes, and snippets.

@huanggm
Last active January 5, 2019 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huanggm/7e04e79a462b23019fd52acd827122e9 to your computer and use it in GitHub Desktop.
Save huanggm/7e04e79a462b23019fd52acd827122e9 to your computer and use it in GitHub Desktop.
浏览器扩展
//content scripts 与页面通信
var port = chrome.runtime.connect();
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received: " + event.data.text);
port.postMessage(event.data.text);
}
}, false);
document.getElementById("theButton").addEventListener("click",
function() {
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
}, false);
//content scripts 发消息给 background scripts
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
//background scripts 发消息给 content scripts
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
//content scripts 和 background scripts 接收消息
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
//content scripts 发起长链接 background scripts 接受;其实也可以反过来(chrome.tabs.connect),主要看使用场景
var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
if (msg.question == "Who's there?")
port.postMessage({answer: "Madame"});
else if (msg.question == "Madame who?")
port.postMessage({answer: "Madame... Bovary"});
});
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});
//add a badge
chrome.browserAction.setBadgeText({text: 'ON'});
chrome.browserAction.setBadgeBackgroundColor({color: '#4688F1'});
//设置Tooltip
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.browserAction.setTitle({tabId: tab.id, title: "You are on tab:" + tab.id});
});
//设置context menu
chrome.runtime.onInstalled.addListener(function() {
for (let key of Object.keys(kLocales)) {
chrome.contextMenus.create({
id: key,
title: kLocales[key],
type: 'normal',
contexts: ['selection'],
});
}
});
//初始化
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.sync.set({color: '#3aa757'}, function() {
console.log("The color is green.");
});
});
//持久化判断隐身模式
function saveTabData(tab) {
if (tab.incognito) {
return;
} else {
chrome.storage.local.set({data: tab.url});
}
}
//https://stackoverflow.com/questions/9515704/insert-code-into-the-page-context-using-a-content-script/9517879#9517879
//inject another javascript file
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
//inject embedded code
var actualCode = `// Code here.
// If you want to use a variable, use $ and curly braces.
// For example, to use a fixed random number:
var someFixedRandomValue = ${ Math.random() };
// NOTE: Do not insert unsafe variables in this way, see below
// at "Dynamic values in the injected code"
`;
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment