0 ratings0% found this document useful (0 votes) 9 views8 pagesExtensions Get Started Tutorial Service Worker Events
Tutorial on service workers for chrome extentions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
© crnmeterdesoner
‘Chrome Extensions
Coot Started *
unsere en evry page
rst srt ito ne ative
Manage abs
Getingied Bg Does + NewinGrame sesh *
Mowle Aelaerce > Songer Crometianstore =
ome > Bae > chametseine > Howe asmenaenr ©
Handle events with service
workers 2
Tt hat con tense ne enc
Overview
‘is tora prove ninaductontoCtrome Extension sence wares As art of his tat, you wil
_nextenson at atows usar to quick navigate to Chrome AP eeroneepagesucngtecmnibox. You
+ Ragiotryurserice ware nd impart moses
1+ Manage state anata eer.
+ ger paras events.
+ Communist with content ert,
Before you start
This gu assumes that you have base web development experince. We recomend evewr Eenions 10
and Heo Word fran introduction ta etanson development
Build the extension
Sto by cating anewciectry cles quickpt-referencetoheld the exersion fies downlod the
scxrezeneerom ou Gti siopesrepetny.
Stop t: Register the service worker
Create te manifest fein there of he prcect anda the felling coc
@ erin Sanescone (
1
ockarount”: (
‘exensons register he service worker nthe manfst which on tkosa single JnaSeret No. Teresno ned
to call navigator servicaorker.regiser() lhe you weudina vet pape
restean anages fdr thon onricadtheicors i
Checkout ho rst steps ofthe Rostng tne teal lea mere abou the extanois metas and icnsin
Step 2: Import multiple service worker modules
‘Ou service worker ements tw features Fr beter maltinabity wo wilimplment ach feature n3
eprate module Fit we need to dele thezervice Worker asan&S Module nour manifest which allwe ut
to import macesin our service wore:
eo
Crestethe sorvice-orker.36 le and import twomodues:
eo
mort * sswonmatox 3
mort *Jawtips. Jo"
Create tes las nda consol gt schon.
eo oo
conte top(“se-omibor$°) console. togC“sw 8850 $2")
Sec lrgertng serps toler about other ways ta impert utp sina serice wera:
He Te torent tose “tpemfale” wre sing sede near forvert chasse
(Optional Debugging the service worker
empsinhow to fte sence wortarlogs.and knw whan thas terminate. Fist flow the neructions to
‘Aer 0 seconde youl seer arka (nace which means the service werk has terminate Click
the" servce wert (inactive) no spect The folowing eration shows is.Dic youre that spacing the service worker woke us? Opening the service wrk nthe devtols it
seep ctv. Tore sme that your enfereon behaves cect when your service wera trina,
Now beak he extortion to earn wero ate errors. One way. tisleto date" rom tte «ae
banibox.38" mportinthe service-worker 1 fe. Crom wil be unable to restr the service wera.
Lcobackts ehomianensins ana rerean the itansin Youwil peo eos
An nian etcor eecurrd ahem fetshing the serot
‘ee Debugging etersinstormore ways debug the enterion service wes.
© contendere tagetotneheranetetee naira,
Step 4: Initialize the state
(Chem wiht down sevice worker thy arenat need We wethe chron
2278s service worker sessions. Fo storage access, Wo needto request permission inthe manos
Fre, svete defgut ggeations to storage Wecan intisze tt wen the extron at reat by
totaning tothe rine. onfastelies() event:57 save cofeute aot sugesttons
hea: conte. onfsetalledscdsstener((ceason }) => (
1 (reason sae ‘anstall) ¢
lehtore. storage lca! stl (
spisuestions: [abe ‘storage’, ‘serapira')
nt
,
ni
Serdce wortersdonthav rect acessto the window cect ae heretore canst use
"indo Locstorape to tore values Aso, eve Werkersare shor ved execution enone they get
‘erminteepestdytrougheut auers browser erion which mses thence with cba
‘S00 Persist data athe than sing goal vrs to lean abou other storage options for extension service
wore.
Step 5: Register your events
_Aleventstaners ned toe staal epsteradin te global scope of te sence works Inotner wares, vert
letaners shout be nertedin async function This way Chrme can ensure that al ever handlers are restored
Inthis eae; ore going touse the ehrene can APL but rt we must eckre the amen ey
tggerintnemanitest
Neyer ans sae are” trnce ie ow ney bares hens ere tal ue
Now rater he ames everstaners athe tpl of te sor. hen te se eras the onaibox
eywerd as inte aderessba felowedy tab or space. Crome wi say 2 cto suggestions baseion
{tekeordsinstorage. The aninputhangea|) event uch takes the cuent uzerinput and 2
‘ugpestRasult objec espns or popuating nese suagestins.
1 basploy the sugpesions after user starts tytn
heen combo enioptChangeé a stan (any (teput, suggest
"ait cone ombos setefanltSigestion
»
font ( apiSugestions |» ant cheowe.st
ent suggestions = aptuggection- rap (apt) =
Teun { contents opi, aeoerspton: ‘Open chrom. S(opt) APT}
ocl.get(‘apaegpertion');
‘
aes (cunsestion):
‘Aer the user nlectsasaggeston,ontmputentered{) vil open the eresponding Crome AP reference
age.57 open the reference page of the chosen At
Cheon. emiboxendnputntered.teL inten ((saput) = ¢
lhrone tabs create|{ url= UM EMME EETENSIONG BOC + Soput});
pantastery (input)
ni
‘The vodetenistory() functontokes the omnibox put andsavest 10 storage 16ee. The way he most
recent scmch ermcanbe udlair sn miso suggestion,
enst {aps
seasuggestions
asugpertione
listryinpt)
tions} = att eon. storage, local. get('aptSeagestion’
rah e(input)
sce MEER OFREVTOUS SEARCHES)
e-Loeal sot apssuggestion® 3):
ter pene tenionsenicenatersconse bath web APndCrome Pha fen excepto Fermere
Step 6:Set upa recurring event
‘hg setTinovt() or setInterva() metiod ar common velo perorm dlyecor parodia
owver tees Ale ean fl becaue the aac wil cana te tars when sence veces,
Instead estensonscanusethe chrose.ara APL
Stet ay equating the "alarm permison inthe marifet Aditcnay, to ech the extersion ps from 8
remote estcloation you need to request persion:
,
Treertensin wi ftcnalthe tips, pickene atrandem andaaveitto serge Mewes an arm ht il be
tggeecencea dey to undate tei. ars ee not saved wan youcoee Chroma, So weneea to check he
arm exeteondcrate Hoss,
fonstupeateTip = syne () => (
enstreeponce » ana fetch Mtps:Jexteneson-ipe.g14th. mets. $800°
Soe
fons randontndes = Yoh sort randn() * tps tena)
‘etura chron storage cal st( (tip: palrandninger) 1)
1 cowok af alarm exist to aves resetting the taser
1 The alarn ight be enoved han the bowser session restarts
syn function ereateAlara() (
nt clara = await chrome earns ge (ALARH MAME)
1 (typeof lore == "nae" )
(chron alares-crate(ALAQHNIME,
cslsyimanatess
ne
rcoters9(0:,
ereotentorat):
1 inte tap once 9 doy
ate eee eeecaererter ees se)
vaypone cna wn est sees ein amon te Free
inometen eee tanec
Stop 7: Communicate with other contexts
‘enantio use content srpts to reedandmocy th content the page, When a ues ets 2 Crome AP
reference page the etesors content sri wil update the page wh the tip ofthe doy sereisaressage to
request the pf hey rom he sevice wor
‘Sat by dain the conta srgtin the mane anda he man ptr coreaponng tthe Creme
Scontent-sersps"
tenes ["hepe:/ developer chrane.con/doce/extensione reference]
Ses Desntent 32"
Cresta nen content i, he elloving coc sence amessage to the sence worker requesting ete Ten,
‘338 auton hati open apeporer corning te extension ip. THS code uses the now web lsorm
Popover AL
(ame > (
1 ence a peszape to the service norker
fenst (tip )
te
ent nav = dcunent. querySelactor(‘-uper-tabe > ea):
enat tame « createonttonnt
“pan stylew'saplay: block: font: var
const popover » createbuettennt(
“ay ide Uip-popover”popover styler"margin: eto:"o6 {tip} eséiv=
“ecunat. bay appndpon
‘av oppena( apne)
no:
function erentetoretennt (hte) (
nat son's new Eofarser()-paraefronstring(nem, "text/hal');
Tefal stepitoadd message harder toour service wore ht zens rep othe content sit wt the
iyTest that it works:
‘erty na the fe structre cf you project ok hehe fotoning:
LL quick-api-referencey
FE images
| icon-16. png
| © scon-128.009
EK content. js
FE manstest.json
FE service-worker.js
FE sw-onnibox.js
K swtips.is
Load your extension locally
Toad anunpackacenersionhcveoper mode, folow thestepsineio wor
(Open areference page
1. Enter the keyed" the browser adeeb
2 ran ta or space
3. knter the campleterame of the APL
+ oR choose famalstotpastsexches
4 Rnanpoge it pen tothe Civome AP eorence page,
Open the tipof the day
Ck ne Tp buton atx onthe navigation bar to open the extortionOverview
eNom Fever arched nwo
@ Potential enhancements
Bas on what youve erred today ryt accomech any of the oloning
+ Exlore another way timlement the omnibox suggestions,
+ create your oun custom moc for spaying he eteneon ti.
+ Open anaxtstina page to tne MONS Web Extensions eerance AP pages.
Keep building!
Conratuationsenrishng tistuaril >. Cortnue leveling up your silsby completing other beiner
@ Potential enhancements
Based on what youvelerned today ryt accomplish any of the oloning
+ Galore another way timlament he ommibot suggestions,
+ Chest you om eso mcd or pang the entero tin
+ Operands page tothe MON Wb Extensions reference 2 poe
Keep building!
Congratutions on esting tition. Continue lavelng up your eilsby completing other Degas
sone
Continue exploring
Te continue your extension sence work erring pth recommending thefolouing ates:
+ Teenonsion sevice aria cy,
oo