create-chuntianxiaozhu
Version:
春天小猪模板工具
102 lines (97 loc) • 2.15 kB
text/typescript
/**
* 咚咚助手全局提示,只可以在background和popup中调用
* @param id
* @param options
*/
export function notifications(
id: string,
options:
| {
message: string;
title?: string;
type?: chrome.notifications.TemplateType;
iconUrl?: string;
}
| string
) {
if (typeof options == "string") {
chrome.notifications.clear(id);
chrome.notifications.create(id, {
type: "basic",
message: options,
title: "咚咚助手提示",
iconUrl: "logo.png",
});
return;
}
const {
title = "咚咚助手提示",
message,
type = "basic",
iconUrl = "logo.png",
} = options;
chrome.notifications.clear(id);
chrome.notifications.create(id, {
type,
message,
title,
iconUrl,
});
}
/**
* 向内容发送消息
* @param message
*/
export function sendContentMessage<M, T>(
message: Message<M>,
callback?: CallbackData<T>
) {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0] && tabs[0].id) {
if (callback) {
chrome.tabs.sendMessage<Message<M>, T>(tabs[0].id, message, callback);
} else {
chrome.tabs.sendMessage<Message<M>, T>(tabs[0].id, message);
}
}
});
}
/**
* 向background或者popup发送消息
* @param message
* @param callback
*/
export function sendBgPopupMessage<M, T>(
message: Message<M>,
callback?: CallbackData<T>
) {
if (callback) {
chrome.runtime.sendMessage(message, callback);
} else {
chrome.runtime.sendMessage(message, () => {});
}
}
/**
* 添加chorme message监听者
* @param type
* @param callback
*/
export function addChormeMessageListener<M>(
type: string,
callback: CallbackData<M>
) {
const decorateCallback = (message: Message<M>) => {
if (message.type == type) {
callback(message.data);
}
};
chrome.runtime.onMessage.addListener(decorateCallback);
return decorateCallback;
}
/**
* 移除 chorme message 事件
* @param callback
*/
export function removeChormeMessageListener(callback: any) {
chrome.runtime.onMessage.removeListener(callback);
}