101 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-04-12 17:04:48 +08:00
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create(
{
title: '添加到书签',
id: "addBookmark",
},
() => console.log("创建右键菜单成功")
);
});
2022-04-08 17:04:13 +08:00
2022-04-11 17:42:00 +08:00
chrome.contextMenus.onClicked.addListener(async function (info, tab) {
console.log(info, tab);
let body = {
name: tab.title,
url: tab.url,
iconUrl: tab.favIconUrl
};
sendToContent(tab.id, { code: "addBookmark", data: body, token: await getVal("token") });
2022-04-12 17:04:48 +08:00
});
2022-04-11 17:42:00 +08:00
2022-04-12 17:04:48 +08:00
// 接收content/popup发送的消息
2022-04-11 17:42:00 +08:00
chrome.runtime.onMessage.addListener(async (data, sender, sendResponse) => {
2022-04-12 17:04:48 +08:00
if (!data.code || !data.receiver == 'background') {
2022-04-11 17:42:00 +08:00
return;
}
2022-04-12 17:04:48 +08:00
sendResponse("ok");
console.log("收到消息:", data, sender);
2022-04-11 17:42:00 +08:00
if (data.code == 'setToken') {
2022-04-12 17:04:48 +08:00
await setVal("token", data.data);
// sendToContent
await sendToContent(sender.tab.id, { code: "setTokenOk" });
} else if (data.code == 'getToken') {
let token = await getVal("token");
sendToPopup({ code: "setToken", data: await getVal("token") });
} else if (data.code == "clearToken") {
await clearVal("token");
2022-04-11 17:42:00 +08:00
}
})
/**
* 向content发送消息
* @param {*} tabId
* @param {*} data
*/
function sendToContent (tabId, data) {
console.log(tabId, data);
2022-04-12 17:04:48 +08:00
data.receiver = "content";
2022-04-11 17:42:00 +08:00
chrome.tabs.sendMessage(tabId, data, res => {
console.log("接受响应", res);
})
}
2022-04-12 17:04:48 +08:00
/**
* 向popup发送消息
* @param {*} data
*/
function sendToPopup (data) {
data.receiver = "popup";
chrome.runtime.sendMessage(data, res => console.log(res));
}
/**
* 设置值
* @param {*} key
* @param {*} val
* @returns
*/
2022-04-11 17:42:00 +08:00
function setVal (key, val) {
return new Promise((resolve, reject) => {
chrome.storage.local.set({ [key]: val }, function () {
console.log("设置值成功:", key, val)
resolve();
})
})
}
2022-04-12 17:04:48 +08:00
/**
* 获取值
* @param {*} key
* @returns
*/
2022-04-11 17:42:00 +08:00
function getVal (key) {
return new Promise((resolve, reject) => {
chrome.storage.local.get([key], function (res) {
console.log("取值成功", res);
resolve(res[key]);
})
})
2022-04-12 17:04:48 +08:00
}
function clearVal (key) {
return new Promise((resolve, reject) => {
chrome.storage.local.remove(key, function () {
console.log("remove成功", key);
resolve();
})
})
2022-04-11 17:42:00 +08:00
}