...// Save default API suggestionschrome.runtime.onInstalled.addListener(({reason})=>{if(reason==='install'){chrome.storage.local.set({apiSuggestions:['tabs','storage','scripting']});}});
...constURL_CHROME_EXTENSIONS_DOC='https://developer.chrome.com/docs/extensions/reference/';constNUMBER_OF_PREVIOUS_SEARCHES=4;// Display the suggestions after user starts typingchrome.omnibox.onInputChanged.addListener(async(input,suggest)=>{awaitchrome.omnibox.setDefaultSuggestion({description:'Enter a Chrome API or choose from past searches'});const{apiSuggestions}=awaitchrome.storage.local.get('apiSuggestions');constsuggestions=apiSuggestions.map((api)=>{return{content:api,description:`Open chrome.${api} API`};});suggest(suggestions);});
...// Open the reference page of the chosen APIchrome.omnibox.onInputEntered.addListener((input)=>{chrome.tabs.create({url:URL_CHROME_EXTENSIONS_DOC+input});// Save the latest keywordupdateHistory(input);});
// Fetch tip & save in storageconstupdateTip=async()=>{constresponse=awaitfetch('https://chrome.dev/f/extension_tips');consttips=awaitresponse.json();constrandomIndex=Math.floor(Math.random()*tips.length);returnchrome.storage.local.set({tip:tips[randomIndex]});};constALARM_NAME='tip';// Check if alarm exists to avoid resetting the timer.// The alarm might be removed when the browser session restarts.asyncfunctioncreateAlarm(){constalarm=awaitchrome.alarms.get(ALARM_NAME);if(typeofalarm==='undefined'){chrome.alarms.create(ALARM_NAME,{delayInMinutes:1,periodInMinutes:1440});updateTip();}}createAlarm();// Update tip once a daychrome.alarms.onAlarm.addListener(updateTip);
第 7 步:与其他情境通信
扩展程序使用内容脚本来读取和修改网页内容。当用户访问 Chrome API 参考页面时,扩展程序的内容脚本会将当天的提示更新到该页面。它发送消息,请求从服务工件获取当天的提示。
(async()=>{// Sends a message to the service worker and receives a tip in responseconst{tip}=awaitchrome.runtime.sendMessage({greeting:'tip'});constnav=document.querySelector('.upper-tabs > nav');consttipWidget=createDomElement(`Tip `);constpopover=createDomElement(`
...// Send tip to content script via messagingchrome.runtime.onMessage.addListener((message,sender,sendResponse)=>{if(message.greeting==='tip'){chrome.storage.local.get('tip').then(sendResponse);returntrue;}});