UNPKG

@ng1005/chrome-extension-common

Version:

chrome扩展通用库--消息与storage

102 lines (96 loc) 2.75 kB
import IActionInterface from "../interface/IActionInterface"; import $runtime,{RuntimeEventBus} from "../message/RuntimeEventBus"; import { KeyValue } from "../types/KeyValue"; import { isBackgroundScript, isPopupScript } from "../utils/Utils"; export class ActionService implements IActionInterface{ $runtimeBus:RuntimeEventBus=$runtime; script:string='content' keys:KeyValue={ onClicked:'_message_action_service_onClicked', enable:'_message_action_service_enable', disable:'_message_action_service_disable', } constructor(script?:string){ let defaultScript='content' if(isBackgroundScript()){ defaultScript='background' }else if(isPopupScript()){ defaultScript='popup' } this.script=script||defaultScript;//当前脚本 if(this.script==='background'){ this.listener() } } listener(){ let _this=this; chrome.action.onClicked.addListener((tab: chrome.tabs.Tab)=>{ _this.$emit() }) } $emit(key?:string){ let _key=key?key:this.keys.onClicked this.$runtimeBus.$emitAllTabs(_key,'action!!'+_key) this.$runtimeBus.$emitBackground(_key,'action!!'+_key) } disable(tabId?: number,callback?:Function): Promise<any> { if(this.script==='background'||this.script==='popup'){ this.$emit(this.keys.disable) if(callback){ callback() } return chrome.action.disable(tabId); } let _this=this; return new Promise((resolve,reject)=>{ _this.$runtimeBus.$on(this.keys.disable,(res:any)=>{ if(callback){ callback() } resolve(res) }) }) } enable(tabId?: number, callback?: Function): Promise<any>{ if(this.script==='background'||this.script==='popup'){ this.$emit(this.keys.enable) if(callback){ callback() } return chrome.action.enable(tabId); } let _this=this; return new Promise((resolve,reject)=>{ _this.$runtimeBus.$on(this.keys.enable,(res:any)=>{ if(callback){ callback() } resolve(res) }) }) } onClicked(callback: Function): Promise<any> { if(this.script==='background'||this.script==='popup'){ return new Promise((resolve,reject)=>{ chrome.action.onClicked.addListener((tab: chrome.tabs.Tab)=>{ this.$emit(this.keys.onClicked) if(callback){ callback(tab) } resolve(tab) }) }) } let _this=this; return new Promise((resolve,reject)=>{ _this.$runtimeBus.$on(this.keys.onClicked,(res:any)=>{ if(callback){ callback(res) } resolve(res) }) }) } } const $action=new ActionService(); export default $action