Validation error doesn’t render on the template with 2 form

I have in my template with a form in which data is collected in 2 Django forms but sent to the view in the same post like this:

<form action="" method="post">
        {% csrf_token %}
        <div class="form1">
            {{ form1 }}
        </div>
        {{ form2set.management_form }}

        <div id='form2set-form-list'>
            {% for form in form2set %}
            <div class='form2set-form'>
                {{ form.as_p }} 
            </div>
            {% endfor %}
        </div>
            <input type="submit">
        </div>
    </form>

The data is collected in the view and validated. To validate, I have validations declared in both forms. In case the validations fail because the data is incorrect, they return a raise (depending on which one or ones have failed). This raise is what should be shown on the screen to the user as an error.

If the failed validation is in the second form, it displays the error correctly and without problems. Now, in the case that the failure is in the first form, the page simply reloads and does not show the error. The data already entered in the form is not lost and can be corrected, but the error is not displayed.

My view is something like this:

def create(request):
    form1 = Form1(request.POST or None)
    form2 = formset_factory(Form2, extra=0)
    form2Set = form2(request.POST or None, prefix='participant')
    
    context = {
        'form1': form1,
        'form2Set': form2Set,
    }

    if request.method == 'POST':
        if form1.is_valid() and form2Set.is_valid():
            # Logic
        else:
            context['form1'] = form1
            context['form2Set'] = form2Set

    return render(request, 'template', context)

How to upload a file xml with NodeJS v18 to a SharePoint Online?

I shouaite upload a file . xml in a folder of an online sharepoint, I only have the client_id the client_secret and the url of my sharepoint. Unfortunately, I can’t find a solution.

I tried to do it with pnp but the version is not compatible with nodejs 18 and I can’t do it with versions 3 & 4. I can’t find other methods or libraries that will allow me to do it.I want to upload my file to my sharepoint folder. Currently there is nothing that works

How to prevent row re-ordering on cell data update using ag-grid

I have an ag-grid table where the data is updated using async transactions. I need to have two modes (toggled by button click): one where rows are automatically re-ordered when data is updated as usual, and another where after sorting by column asc/desc that order is then preserved through updates – effectively freezing rows in place.

Is this possible to achieve without some sort of hacky workaround?

I’ve read through the ag-grid docs, and not found options for maintaining row order without just disabling sorting

How to mock IPC calls in electron when using WebDriverIO with Mocha

I have an electron-vite-react application that has several IPC calls from browser to main process. I want to mock the behavior of these IPC calls when I’m writing e2e tests for the app using WebDriverIO framework with Mocha tests. I have tried several ways described in the docs, but could not get it worked. Can anybody explain how do I start with this?

For example, I have a function in my react part like this.

export const isConnectedToCloud = async () => {
  const cloudUrl = await window.electronAPI.getCloudUrl()
  console.log('cloudUrl', cloudUrl)
  return cloudUrl !== '' ? true : false
}

It is called inside a useEffect of a Component to render different views based on the output. Now I want to mock that behavior in my test file which looks like this;

describe('Display Connect/Disconnect buttons', () => {

  // Case 1: Cloud is connected
  // TODO: Mock the isConnectedToCloud function to return true
  it('should show Connect button', async () => {
    // button is inside a div with id cloud-connect
    const button = await $('div#cloud-connect button')
    // button should be displayed
    expect(button).toBeDisplayed()
    // button should contain text 'Connect'
    expect(button).toHaveText('Connect')
  })

  // Case 2: Cloud is disconnected
  // TODO: Mock the isConnectedToCloud function to return false
  it('should show Disconnect button', async () => {
    // button is inside a div with id cloud-connect
    const button = await $('div#cloud-connect button')
    // button should be displayed
    expect(button).toBeDisplayed()
    // button should contain text 'Disconnect'
    expect(button).toHaveText('Disconnect')
  })

})

Appreciate the thoughts

PDF encryption image color corruption: should i encrypt hexa string inside an array value?

Here is my obj 17 encrypted, the ColorSpace value is the same as before encryption, so should i encrypt the hexa value inside the array value ?

17 0 obj
<<
/Length 5696
/Subtype /Image
/Width 327
/Height 113
/ColorSpace [ /Indexed /DeviceRGB 251 <0000000000000000000040004040402B2B2B242424202020171717005595152B152B2B1524242400609F2020201E1E1E1C1C1C0059991A261A2424182323172020201F1F1F1C261C005B9B1B241B2121212020201F1F1F1C231C23231C22221B21211A2020201F1F1F1F251F1E241E1D231D23231D22221C21211B00609F20201B1E231E1D221D22221D20201B1F231F1E231E1E221E22221E21211D20201C20201C1F231B1F231F1E221E1E221E21211D20201D00609F20231C1F221C1E221E22221E21211E21211D00609F20231D1F221C005E9E1E211E21241E20231D20221D1E211C21211C21211E21211E20231E00609F20231D20221D1F221D1F211C1F211C21231E20231E20221D20221D1F221D1F211D1F211C21231C20221E20221E005F9E20221D1F221D1F211D21231D20231C00609F20221E20221E1F211D1F211D1F211D21231D20221C20221C005F9C1F231D21231D21231D20221D20221C20221C1F211E005FA01F231D21221D20221D20221D1F211E1F231D20221D20221D20211C1F231E20221D0061A020221D00609F20221D1F231C1F221C1F221E20221D20221D00609F20221D20231D20231D1F221C20221D00609F20221D20231D20221D1F221C21221E20221E20211D20231D20221D20221D1F221D21221C20221C20221E20211D20221D005FA01F221D21221D20231D20221D20221D1F221D21221D20221D20231C20221E20221D1F221D20221D20211D20221C20221E1F221D0060A000609F20221D20221D20221D1F221D20221D20231D20221D20221D20221D1F221D20221D20221D20221D1F221D21221D20221D20221D20221D20221D20221D1F221D20221D20221D00609F00609F01609F01619F106AA5116AA5116BA520221D2074AB2174AB2175AB307EB1317EB1317FB14088B74188B74189B75092BD5192BD609CC3619CC370A6C97FB0CF80B0CF81B0CF8EB9D58FB9D59EC3DB9FC3DBAECDE1AFCDE1BED6E7BED7E7BFD7E7CEE0EDCEE1EDCFE1EDDEEAF3DEEBF3DFEBF3EEF4F9EEF5F9EFF5F9FEFEFFFEFFFFFFFFFF> ]
/BitsPerComponent 8
/Intent /Perceptual
/SMask 34 0 R
/Filter /FlateDecode
/DecodeParms <<
/Predictor 15
/Columns 327
>>
/Interpolate true
>>
stream
*eÜ¥Ìm}äÓ ¬håË>ñc³ßTyÜwwŠ?NìÛùúÀèÃ2$íy:ΚbŠ›X _¼¥ÎÔ
ÌÓs{œ²i…Ã¯ŠŠR4ö˜ö§ÇìZ>MæZDœŸ¼ög[øAôSi#‡ôUrÓ`@IùËÔ¹o–PÚ®°Š«q¢fpН¤zX™!×  Qx/ÍÚÂý%åðr)HÎ¥ã>”1K$w¡~%§Á˸«£‡¿ªq'bj
šVÅ   ¾|hRrºßÔ6!¤c¤Ö †)¯d«¦&Ä-ä*
<cžàŸÃü_tÖX×§)Œ.BnV“c{Ÿ'yâ9ëü×J¸ÇòáÉ    %ðÔùaÝü   ®eùkI+¤m’Žs¸Þ{cÅ#j¡†j̲^£˜;×Âi2Ñ,FÛ‰õ™«ªi)íÖ6A w‹[Òaª^´[ïª1ç2çÍ÷& ˆ¢¯ŠÃ¦iõa*¤îRª7B #ü²:Ê•¦Bíqló«ŸÖ¶  ^iÆØh_§Ú$ÉÁ±ŒJ÷‹¥   JWJ}‘ïƒÂõÛ²ö9¾EÞšfgHaë´mÍ1-æHΔCg!tšI,¤
^辩ÓÐóÎI@ïj‡ZBr> b%ÄÆt ?]kþ$î…9þc+Ëk®Hš/T
†lóˆG9«EX1¡Xjº®í…ãL£q’Gçï%¨é´ÇÁ} ®Çð'†þ°d¤•qè¯$÷¤´‘œžÄ×Dº¤ÑÊD½’m`žu=ªmÖ
úÎîjÓ15¯Þ.H”÷ix£IA­›öeÆsxœÿ*k“îzž«`þh:©8uá}Žû9‘õÿ榲OTþHa'!e`ÙÄÒ=Y—KÄrå)À:YEð#?ÇX¬¿–m×θÜO£’ìé¶unâ
¯&L‚ ÚknÎńɳÈ%
´H:e…lfã06„‹­ï#zôé tˆ×Q¬îBQèäcYÌú~¥ûA?É“ÉM”`.DÔ€8Kqº_1HK‰:D…Z;® t>ï«SdÛ ÛÃÀÛèï‡>Lõõäõ'ý‘T>?ƒÔ)®æœnºƒÁƒze†ÝO‹Ñ    źÖ7´IwP"¦1GÞ¢ÛX̼˜HhZX‹‡“¯4Â<eEÆÔ‡_T…qõšìÝó:èæ¦c<Á—bsblþQê’ˆè¡ùSc-“ÆÍ½íÉÀ?K,Ÿ]wb²Š¶r0Vƒ¢[ S;eîü§`¤ýÓU¿c³?Á¦…20oô€a^?¥¸®ažhjŸv:ë«*`Ó¶¥Ü•k“G?ŒV¬p¾.¬ÊqŒ}×YžÙ˜Þ2U•ôÒ§©m.'   U':´2xýBÍ&ì‹ßì$3´BZœ6»z|¾=t
-Y$›èú5ã(ÄAòõ¹a÷Ýí3Bòè?Ù{Agõ¦“þeÂEÃXM¢{«ìÏOuLª“(~…Œ#R·u2…ßÚbr@)˜Á^ÆïÎóYÒq&Ñ÷yWùF+v%yñ¼c¤lÀVKÄ‘÷vß½¾oã±l:#ßéùä—“#l}û¹9»ƒÌczwH¢5ô“›p®Ã'µè•-¢ÁsîžGÖ7‰ÓæïÄ9µ†+`­¿‡:‚ºðŽ•™Ì  ÁòÄòšúκlPŠý•L+o8ç+å݆toÄùX?¢œ>á‚v&PZ‡^ –÷3Æ1…&<XU   ¢`ˆ^<&¹Ì÷ȉN« nºwRœ÷hŠa’ª€ Œ
û.(¾¡ñå…~WNÊr¸"Óö‘ç[¨DqõðEn“Ý`ìlù¦&.à¥ÅGÃXGí„zŽ?@2Y¢¹šš¬ëÅ¢R‘·›I{eHÿëÈñBPÓÚ´~#úg¡Orº•µ7¯ ô•ÉÃ$N9«h^¨êæcgÙè©«Ï«y­sŒü}Û³q¬Zwˆ-M#ßÈ»',T}U¿"𣊛3€Œ÷–‘[—bÛI%.4ÝHì]äÕèk    mois#¦!~¹hzFÉäal{`"cïlŸòò™aÓ{d^R†ëúOFŠ"oç°]ð#Ù¬ÞÀ†jÌO#ñˆ-†WR=w6kXÖå GH¡bÉg)7ÀTè•qo$jv”E˾ÀQ½ð h/ë/ü+|z
ø8|BJðŒ³ìX ÐÈ´9d*áë„i@Å€¼çÜ?ŸKt¤o<­âæË­®í_õµc
N{HYm+$éV¡ èãÊ´}  ö€à±H—îPm·Š9qQ;Ò  ²E©÷úo•Û+®ìkÓäìm­òPçO¢Þ¿†h~H°­HPæG½uÜÚéðn…
/p7¡8±þ)…U£ï–Õ9õTt íç~k““£Ýl·m=>•ØÖ³Äi›îg§Ú7”Æ{vÕ¡kPšæÖ'ƒP»¿3+ٖıµ>³,YaÜZ7ÀÂãxâ$FZ+ÐJÃß©!>q%¼ê~ÂgÙÉþqZyÇÇzÚòÁ]q¬  y`ó…mdÎ_Ö­~8Ya!|ïÚd MR$b»Š§b(*pŒ®ÈtÀæÆ„IK-*´vôO²ºunÌùDð‚YcJP×õI|½3Ô5Hó‹ÖN˜ BúJB•î«T;Ú7'(Õ^N`Ît±4‹‹ÃJ+
ëC
ÄìábªÖa¼Ð
Êvê#¢oÄÈ0(1ÉÂŒ*iÇbu¸¹…%LQ"¦Ä(?ªèja›<§´.ê/Ï»qµJ`ÀI»º_Ök¾!nHµ.HFX°æ1Ð6u   þ§›lCxCuÿù%=WˆÀCíÆÅãë›Aéäæ¼Iü+G‰Ñ^Ž"
’Ô‹¥ß¥3ñˆ Üdk~fµve æ«P¥¶–2¦¦¸aϽ{úAC×$WºÐÑéoECïP4Ir^ÀnDzò®]3·s;ÄyÃ,ý`s~ÖrZ±_NqqÆMÜj˜=æx$RŒò¤û:þùÒŽË
ªó—gèñr>Û4[Ä5Áö×<JA¾´0Îë _!¡ïQË……êMz7 ¶ žYý^ÇP¡ŒÌž½¼Ç
篕xÇì¼ï¦Ù~´ð úI¡ªÎÿøÒIEÑc=w  Ã"¤Xäígy½ÎýjÕáp¢ÞìIÄ~M<§4ÿÜ÷y¨Ó•Jâçhºè2Sl„=‘åãþ8Úàˆ™þÙk$   wµ-BU:›ñ„èR{s¥œ­âêgÏlzv㶉oز_̯Yumר¦Ä(Üð®xFŠGcý5Ó#š´øÇ—"ØïÁÆnõ-ľu¯¿^a@|Û[42×tEFŠÉ_‰Ëò-Tsˆð”ñªE‡ù&1uÖ´y’“»Ç#‚ÖÏ}y†}îÙáLíD²Ã WÎ1QCŠÍ{ÔB`A´©/šQ†íÏXOêK#Lh<   b®™)iœ¢ñ0ŸäÈ/ÎÃÑd¹µˆÿÞöŠ@%&ØÈ‹¾åyë}Õ©n…m6s¸pP½×8c?‹u¯D-@!©eg([¹HÕIY°R½1æœ]Y­âíét#®XȪ¡Wì]›{ÅÄe¤?}“S ˜º§ Ü
|>]B¦U†ÜÏ4E,ç—ÀÇ,tŸÐKäÐN¹‹X«ÆÎe’Îô&dŽÀg‰Ñ›«“5$šLþCŒ{"‘§v1KâÆÆš%,p.­¶¹vRÍÛ7‚s²§::ª±Ð²" lÆmIc!¶qz*SI$ÂÜšs¤x
:ø¡oRluÇ•ÀhÐËQéÌÞÔQº'ÇL¿ƒÙ›¦
Í
 ªöF–FjšÎ4§»ƒâÐ÷àóZO8-Û Ñud½6ƒ ¾ /ïþã->=äj½ŠŠÕs=Eyœ­ß)0ú–ëØß¼$"jMËvø¾kX¡;K|'a^$Y0ù’;JI£ÁÒ±Ÿ¤‹‹4

,_Ö+ÅMqC]-“ê»Ü²Ô¦]‘,—ìuXòx
":R§ØS_ö±Jªé³G½ÝCÒÅ:£Ø©iÌ,¦¢ØRÄ˜Úææsc.fPà
˜¥l@ým9Ó¢»ah¥Nyii5¢lþ.GÆ2s¡„Ù
»¿Àn®Üø[£Þíx‰a“¨Üõò¦‚vBgÑšŠ•¾©Êä´&NŠ]¾k|Þ²9;F%´‚2p6-!Ýû 7}Ï„í31>Šó³õ¡ ^¦Ä½"Ÿ{
ªéa%ðCÌåb¢MIeÏÕ4¤«ªiïÙ×´-¶F:¥W3uãœLoƒ-]0JIƒÁÑêæ•»©T3¾á#àžÒŠ¡è>Á•¹Œ!‰@œçd¡cmŒmŸ¿&¼‹ÄË]|¿WÝ_¿–³u„Ѝ H0@cðÞjñÓ®ý%»®Z“O?ÿÕ*Ï[®×‚“)še‘›É•ôˆÆFþh[¡~Šë. ¹¨ÿŠjÇe¢¬Ïëe[·gц%wŸG¦øÞßËi¿ßh'jE&UðÍã_ô(ô¼¬ç{‡KH÷<©FßNÚ¾‰9 Ó6ÑO× HxËÜÑÄ™ÍÙ;#­³7Mz<íHlpb7ùwÂ^ÖˆAï*ò»kíR±ªAk|whß}°ŠþµvA(n–Y­=ý›ÊI¿ÒZjw|Á’{ŠYÃ{§ÅLžø;à–'`‚ý›4¼Ý7óØØn©JDšY*Ç=ôéFmŠý–¶ÜŠºÉTu*áƒk_œí×eW9MñGgœ<CFé±Uàù !‡P|5òStbv]Þd@‘úDô<ä'µWð}¹ÑKãö÷Ï? ‰ßÖ]ÌDÊ9*ÀqxM™]2o`ÍOlð!ÓZ?­riu¤5¹ÆÇ¹-åÈ¿a«h®qpGi:œtcLm5æÏêŒ'a+¨ŠMÈ`÷/Ë­¥R‰é6s×ÝæIàæ;¯´
DØ#Ù#«›&2˜tÉTèÒ”}_GìÖŒ§¸zfêý|ó8¯æ¤=^B@ÂðÝOªH©3¦;ÐÞ
ÈÒ~£ï',<³šâ•’
]b¨OQ÷s–l¬¢“5q•=!<’Üùv®3:k·Bޝå4y+6‡&E]ƒat9>`oÝú èa;ãų©¶ÛÍÜ…Šhöž]s+x™dŸqûLÒΉ¯GÍ¥ö¨QâxÞ:a›s;ðíÒÚxéä0ËMX¡ßS··*â¿ÛwTëXknLjC-¦úÎs
1…“ÐYi
¼`…0Ì+µWñtƒ~þ9yL‚ùJÄ0m¼ÖêÑû™ïFÂi£ËËØ@a²'9å v†:ä÷    jõpO)·ô°½v Tñ¯¸‘3ž»éÿ†@·¢æŠWÏ#-{t‡žº!an,Ia³i¨Y·ýmíÐÍeàR©”‰^Zø5~)A³)lf[¿Ù`ïXÿZ'8½!éÈ)mü-S®ýD~X¢§`kì³ÕKóâþfP)×2†ùÛºïÕé8”ð=üŠ@œvŠy`a@)
xï3½ª¾ZòÄ–Ž~OŽTDÕß™*íP’()ÔûE]Íò¥ˆG@Î á^0c¬‰M|VùýúÇ-ÜàÚ°;HkxZ!Ù»6ÄÏ1žîèrÓÜäƒÞèÇkÕ’Œjóˆ
øæ*w¸fñCÏÜd’x$PæøÜÄ,Ý€áœe¥ÃºçM3›/ûƒ‚÷ÇýA1^g»z=_{Ð8Ò!Áø    ßýÙñ"3¢£˜<T|õR‡'ÀH –ÍÒÝð:n9?Ì®{úgŠW™zåZ¸®÷GÇ<+jaZD(Ý7PöOU>’6âÜ#™fYX)`ôT hX…àÔØÅª@&ƒ+`™Û±²Ð”îCNì gÕo£4ÞµÔÖ­ÔÑE&¹ÜÄcª5D¿~
±ó*$‹]Ó«¼À.µ0§µ:yxµŒ=],Ç4©âM‰gñ/ÞâÔkʃ•C‹õн¦0ZìßÉ¢ÛV¼úÊ#%+ûKM^;{yEQ6Ð6{uÓNÃt—{é8¨—ô‘ÇÍxÚ(Ù‘Iºp¥AA3µo¤kµ«@ƒÒ·µn©Í‘j–q0ˆc
æÏ°Ø÷ùöýjdó7[y†tÒh>ÑÒ®î1áz£ P§€(ºÏz÷Ä»[EëCyöv剘¤ääþ¹j_ˆc×LÔ]|¢ÿšÉ
¯PåFúuɾŠs§öaå½JFc†Š}5‚ÆÑr2#ODbÓµ”›Áz¿   šÝ?«/¶øÍÛ`ú߯CXP?[”މœ­‚$ï¡™G›ý<¹RÚ‘×w’TÝFBÏŒG   ¡_«z<J%/+?Ë(ÝëgùéQr)ðRʹq[
êî†:Õö.@ÿªý:d’wTÇH,¶¦Ÿ=A§¾ÛYûÁ§šbW#£]¥¬R5ÝwÏÞ¬z‚,Ú˜n-ël tðW‘·½Gqd¸ìнt2ĶlŽæøx:›tí
°Šú¸e¸¼05¡SuT@ýQ­E•øÊ$΄šÏJ— ¿žè
9.j4â€wpš é†~*—øœP…¹¼ñtà绀÷€^«Û‹Ë¢î®ùú<juSʨ{樂½õ±Zð¦À{…ÞÝoùh¢•dŸv¯ÄdøÁ–kH¦Æ»rµû›ò¼@yø#Í`+ÆB/†™¢eq¤†1H!ýr÷ÐÉðv¿ÃHªaæeuì__ÃQ3Œ·ËN¯_{ìJa$ç¢×l7L¥ˆÄ‘§Áö‚»¾Ñ–ŒË¡› EŒ=êÁ´k‹
b‹B
†ÿÿåQ,šò/‘ð¿ðqu–®º¥k(€’ŠŠ
?úÇt³Òu:ºƒ³’ÑÎ9Ù¡Ž 6ÖïØKø$—JQxge2M,T£¶öœsŽÁf[Q#§ïþâ¡%P»¬½¾
g?žÂR¡—þ/ZšÒðA‰î{WÄÙh)ä¯Zß•ÇÃÕs6{y¡„m[áÝq[½Þc'¯¾Ê£…sÌ)ó«ÐSæƒ=¿çfåñ7ü›   ü?5ÅÙš8‰¼0ìy²}Åêài ÅÜ…ÿnÞØ%)²­ÓY<ο©²ÏžþÚÁO:ú¡«àÜ©`Å B0…ˆ¶ñ–ƒ¢H@x×¼Àt¤`Ý={„*ë°æ)Áö™>K5-ÂÆ
‹ž§7ó#¥›9†ÉR»Áûd…{ÛL(<  žšXVNí¬®¬F®;<&÷JRÂO
zˆñ¦é®–½çLÕÂCQÁ¹«¾ÏmÒ¹£5!]‰EvΧêíé.ˆ-Aë ™_MȘdî÷˜”Wx|jb ØR
n7coìð¾¡uM[–â2ëÙ
ÌtU8?gÙ=nö—ˆ™ÂÅz'„p?
endstream
endobj

I use pdf-lib.js with pdf-security.js (with code added), it works, the pdf is encrypted, for others pdf, but in this pdf the i have 3 images, the 2 images colors are not corrupt and i noticed that they have no array (/ColorSpace /DeviceRGB), but this obj 17 have and array as ColorSpace value with an hexa value inside.

keyboard event argument despite being ‘Enter’, is not ‘Enter’

While trying to expand the interface of my JS calculator project, I decided to add a keyboard interface so that you can write directly in the input box with your keyboard. I also decided to have an option to press the enter key and get the calculations processed and directly displayed on the input box.

When I made a function to check the keyboard event, it showed that the event was not ‘Enter’, even though the key I pressed was enter (I console.logged what the event was, and was it enter?. The first log showed the event is enter, the second log showed that the event is not equal to enter). Here’s the code of the function-

           function key_type(event) {
            buttonElement = document.getElementById('input').value
            if (event === 'Backspace') {
              if (buttonElement === '') {}
              else {buttonElement --}
            }
            if (event === 'Enter') {
              equal()
            }
            }

Here’s the code of the whole program-

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Oncalc</title>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">
        <style>
        body {font-family:Poppins;}
        button {padding:1.5%;margin:1.5%;border-radius: 10%;border:none; transition: 0.3s;}
        button:hover {background-color: #cccccc;}
        #operator {background-color: #ff6600;}
        #operator:hover {background-color: #d7671c;}
        input {
  float: right;
  width: 70vh;
  height: 15vh;
  padding: 10px;
  font-size: 7vh;
  border: 0.4vh solid #8d8d8d;
  border-radius: 1vh;
  box-sizing: border-box;
  text-align: left;
  outline: none;
  transition: 0.5s;
  margin-right: 15%;
  font-style: italic;
}

input:focus{
    border: 0.4vh solid #d7671c;  
    transition: 0.5s;
}

input:placeholder-shown {
   color:#8d8d8d;
   transition: 0.5s;
}

input:focus::placeholder {
  color: #ffae79;
  transition: 0.5s;
}

        </style>
    </head>
    <body>
        <button onclick="buttonElement += '1';" onmousedown="showtype('1')">1</button>
        <button onclick="buttonElement += '2';" onmousedown="showtype('2')">2</button>
        <button onclick="buttonElement += '3';" onmousedown="showtype('3')">3</button>
        <button onclick="buttonElement += '4';" onmousedown="showtype('4')">4</button>
        <button onclick="buttonElement += '5';" onmousedown="showtype('5')">5</button>
        <button onclick="buttonElement += '6';" onmousedown="showtype('6')">6</button>
        <br>
        <button onclick="buttonElement += '7';" onmousedown="showtype('7')">7</button>
        <button onclick="buttonElement += '8';" onmousedown="showtype('8')">8</button>
        <button onclick="buttonElement += '9';" onmousedown="showtype('9')">9</button>
        <button onclick="buttonElement += '0';" onmousedown="showtype('0')">0</button>
        <button id="operator" onclick="buttonElement += '(';" onmousedown="showtype('(');">(</button>
        <button id="operator" onclick="buttonElement += ')';" onmousedown="showtype(')');">)</button>
        <input id="input" placeholder="Ex - 1+3" onkeyup="key_type(event)">
        <br>
        <button id="operator" onclick="buttonElement += '-';" onmousedown="showtype('-')">-</button>
        <button id="operator" onclick="buttonElement += '+';" onmousedown="showtype('+')">+</button>
        <button id="operator" onclick="buttonElement += '/';" onmousedown="showtype('/')">/</button>
        <button id="operator" onclick="buttonElement += '*';" onmousedown="showtype('x')">X</button>
        <button id="operator" onclick="buttonElement += '**';" onmousedown="showtype('**')">**</button>
        <button id="operator" onclick="backspace('1');">CE</button>       
        <br>
        <button id="operator" onclick="backspace('all');">C</button>
        <button id="operator" onclick="equal();">=</button>
        <script>
           buttonElement = ''
           function equal() {
            document.getElementById('input').value = eval(buttonElement);
            buttonElement = eval(buttonElement);
           }
           function showtype(char) {
            document.getElementById('input').value += char
           }
           function key_type(event) {
            buttonElement = document.getElementById('input').value
            if (event === 'Backspace') {
              if (buttonElement === '') {}
              else {buttonElement --}
            }
            if (event === 'Enter') {
              equal()
            }
            }
           function backspace(cut) {
            if (cut === 'all') {
              document.getElementById('input').value = ''
              buttonElement = ''
            }
            else if (cut === '1') {
              str = document.getElementById('input').value;
              modify_str = str.substring(0, str.length - 1);
              document.getElementById('input').value = modify_str;
              buttonElement = buttonElement.substring(0,str.length - 1)         
            }
           }    
        </script>
    </body>
</html>

I will be extremely grateful if you could help me.

Infinite Loop with rxjs: Error: Maximum update depth exceeded

I admit this is a going to be a beefy one, so I will offer a bonus 100 (via bounty) points to whoever can answer it. I have started to work on this codebase, and haven’t used RxJS before, though I think more the issue here is how the dependencies are working, rather than a RxJS issue.

THe line that causes the looping to be triggered is in SelectorColumn and here:

  const { reduxSelector, unwrappedItems, mapper, emptyMessage } = hydrator(
    columnData.item,
    columnIndex,
  );

I am not sure if the hydrator is a concept in RxJS but I could not find anything on it. I have then tried to go backwards through components to see where the rerendering is being triggered. But without any real state that I can see, I get lost.

LocationSelector

export const LocationSelector = () => {
  const currentLocationId = 2;
  const dispatch = useAppDispatch();

  const [locationSelectorState, setSelectorStateFromObservable] = useState<
    Map<ItemId, ItemCheckedStateTree>
  >(locationSelectorState$.getValue());

  useEffect(() => {
    const subscription = locationSelectorState$.subscribe(
      setSelectorStateFromObservable,
    );
    return () => subscription.unsubscribe();
  }, []);

  const handleSelectorDone = (state: Map<ItemId, ItemCheckedStateTree>) => {
    setLocationSelectorState(state);
    setLocationSelectorVisible(false);
  };

  const handleSelectorCancel = () => setLocationSelectorVisible(false);

  // TODO Bit of an issue with the Selector in general – it is not reactive.
  // If the state of this LocationSelector component changes, for example,
  // this hydrator is not re-invoked. This means that the Selector will not
  // re-render. A small knot in the logic which we have worked around here, but
  // a 'useSelectorHydrator' hook would be a good idea.
  const hydrator = (
    location?: SelectorItem,
    columnIndex?: number,
  ): SelectorHydrator => {
    const locationToSelectId = location?.id ?? currentLocationId;
    if (columnIndex === 0 && locationToSelectId) {
      dispatch(
        locationEndpoints.getLocationDetails.initiate({
          locationId: locationToSelectId,
        }),
      );
      return {
        reduxSelector: locationEndpoints.getLocationDetails.select({
          locationId: locationToSelectId,
        }),
        mapper: locationDetailMapper,
      };
    }

    const query = {
      immediateChildrenOnly: true,
      locationId: locationToSelectId ? +locationToSelectId : undefined,
    };
    dispatch(locationEndpoints.getLocations.initiate(query));
    return {
      reduxSelector: locationEndpoints.getLocations.select(query),
      mapper: locationMapper,
    };
  };

  return (
    <Selector
      hydrator={hydrator}
      state={locationSelectorState}
      title=" Location Selector"
      icon={faCrosshairs}
      onCancel={handleSelectorCancel}
      onDone={handleSelectorDone}
    />
  );
};

MetricsBuildQuery

interface Props {
  isShowingResults: boolean;
  setShowingResults: Function;
}

const dateFormatString = "yyyy-MM-dd HH:mm:ss:SSS";

export const MetricsBuildQuery = ({
  isShowingResults,
  setShowingResults,
}: Props) => {
  const currentLocationId = 2;

  const dispatch = useAppDispatch();

  const { data: locationDetail, error } = useGetLocationDetailsQuery({
    locationId: currentLocationId,
  });

  const [selectedLocations, setSelectedLocations] = useState<SelectorItem[]>(
    [],
  );
  useEffect(() => {
    const subscription = selectedLocations$.subscribe(setSelectedLocations);
    return () => subscription.unsubscribe();
  }, []);

  // Set the query metric for API call =========================================
  const [selectedPointIds, setSelectedPointIdsFromObservable] = useState<
    number[]
  >([]);
  useEffect(() => {
    const subscription = selectedPointIds$.subscribe(
      setSelectedPointIdsFromObservable,
    );
    return () => subscription.unsubscribe();
  }, []);

  // Pre-fetch the assets for the selected locations ===========================
  useEffect(() => {
    selectedLocations.forEach((option) =>
      dispatch(
        assetsEndpoints.getAssets.initiate({
          locationId: option?.id as number,
        }),
      ),
    );
    setPointSelectorState(new Map());
  }, [selectedLocations, dispatch]);

  // Set first location as selected ============================================
  useEffect(() => {
    if (currentLocationId && locationDetail) {
      const currentLocationSelectorItem = locationDetailMapper(locationDetail);
      setLocationSelectorState(
        createCheckedItem(currentLocationSelectorItem[0]),
      );
    }
  }, [currentLocationId, locationDetail]);

  // Time range ================================================================
  const [timeRange, setTimeRange] = useState<TimeRange | undefined>();
  useEffect(() => {
    const subscription = timeRange$.subscribe(setTimeRange);
    return () => subscription.unsubscribe();
  }, []);

  // Location Selector visibility ==============================================
  const [locationSelectorVisible, setLocationSelectorVisible] =
    useState<boolean>(false);
  useEffect(() => {
    const subscription = locationSelectorVisible$.subscribe(
      setLocationSelectorVisible,
    );
    return () => subscription.unsubscribe();
  }, []);

  // Point Selector visibility =================================================
  const [pointSelectorVisible, setPointSelectorVisible] =
    useState<boolean>(false);

  useEffect(() => {
    const subscription = pointSelectorVisible$.subscribe(
      setPointSelectorVisible,
    );
    return () => subscription.unsubscribe();
  }, []);

  const [hasPoints, setHasPoints] = useState(false);
  useEffect(() => {
    const subscription = hasPoints$.subscribe(setHasPoints);
    return () => subscription.unsubscribe();
  }, []);

  const handleRunQuery = () => {
    setPointQueryPointIds(selectedPointIds.join(","));
    if (timeRange) {
      setPointQueryTimeRange(
        format(timeRange.customStartTime, dateFormatString),
        format(timeRange.customEndTime, dateFormatString),
      );
    }
    setShowingResults(true);
  };

  const ChooseLocationsMemo = React.memo(ChooseLocations);
  const PointSelectorMemo = React.memo(PointSelector);
  const LocationSelectorMemo = React.memo(LocationSelector);

  return (
    <>
      {/* TODO Need to memoise these components */}
      {locationSelectorVisible && <LocationSelectorMemo />}
      {pointSelectorVisible && <PointSelectorMemo />}
      <Paper
        noPadding={true}
        header={
          <PaperHeader
            title="Build Query"
            icon={CalendarTodayOutlinedIcon}
            toolbar={
              <Stack direction="row" justifyContent="flex-end" spacing={1}>
                <Button onClick={() => handleRunQuery()} disabled={!hasPoints}>
                  {isShowingResults ? "Re-run Query" : "Run Query"}
                </Button>
              </Stack>
            }
          />
        }
      >
        <div tw="flex m-4 gap-6">
          <div tw="flex flex-col gap-4 flex-1">
            {/* TODO Need to memoise these components */}
            <ChooseRangeOption />
            <ChooseLocationsMemo />
            <ChoosePoints />
          </div>
          <ChooseRange />
        </div>
      </Paper>
    </>
  );
};

SelectorColumn

const dummySelector = createSelector(() => null);

const defaultStyle = {
  width: 224,
  height: 400,
};

export const SelectorColumn = ({
  hydrator,
  onItemsFetched,
  checkedState,
  onDilateItem,
  onCheckedChange,
  columnIndex,
  columnData,
  highlightedItemId,
  leavesOnly,
}: Props) => {
  const [items, setItems] = useState<SelectorItem[]>([]);
  const [itemsAvailable, setItemsAvailable] = useState(false);
  const [filterInput, setFilterInput] = useState("");

  const filteredList = useMemo(
    () => {
      return items.filter((item) =>
        item.description
          .toLocaleLowerCase()
          .includes(filterInput.toLocaleLowerCase()),
      )},
    [items, filterInput],
  );

  let isLoading = !itemsAvailable;
  let data;

  const [springs, api] = useSpring(() => {
    return {
    from: { left: columnIndex === 0 ? 0 : -defaultStyle.width },
    config: {
      duration: 200,
    },
  }});

  useEffect(() => {
    if (!isLoading && items.length) {
      api.start({ to: { left: 0 } });
    }
  }, [isLoading, items]);

  const { reduxSelector, unwrappedItems, mapper, emptyMessage } = hydrator(
    columnData.item,
    columnIndex,
  );
  const selectorResult = useAppSelector(reduxSelector ?? dummySelector) as {
    isLoading: boolean;
    data: any;
  };

  if (selectorResult && isLoading) {
    isLoading = selectorResult.isLoading;
    data = selectorResult.data;
  }

  if (unwrappedItems) {
    if (unwrappedItems.length && !itemsAvailable) {
      setItems(unwrappedItems);
      setItemsAvailable(true);
      onItemsFetched(unwrappedItems);
    }
  } else if (data && !itemsAvailable) {
    const fetchedItems = mapper ? mapper(data) : data || [];  // Fallback to empty array if data is undefined
    setItems(fetchedItems);
    setItemsAvailable(true);
    onItemsFetched(fetchedItems);
  }


  const transRef = useSpringRef();

  useEffect(() => {
    if (!isLoading) {
      transRef.start();
    }
  }, [isLoading]);

  const renderSelectorItem = (props: ListChildComponentProps) => {

    const { index, style } = props;
    const selectorItem = filteredList[index];

    // Safer to use item ID rather than index here?
    // I mean, the index is as unique as the ID, so perhaps it doesn't matter
    const handleCheckboxChange = () => {
      onCheckedChange(columnIndex, selectorItem);
    };

    return (
      <div
        key={selectorItem.id}
        css={[
          tw`flex h-10 justify-between items-center px-4 border-b border-component-dark-1 w-full gap-1`,
          highlightedItemId === selectorItem.id && tw`bg-ctrl-bg`,
        ]}
        style={style}
      >
        <div tw="flex gap-8 w-full overflow-hidden">
          <Checkbox
            label={selectorItem.description}
            checked={!!checkedState?.get(selectorItem.id)}
            indeterminate={checkedState?.get(selectorItem.id) === CheckedState.Indeterminate}
            onChange={handleCheckboxChange}
            disabled={leavesOnly && !!selectorItem.childIds}
          />
        </div>
        <div>
          {selectorItem.childIds?.length && (
            <FontAwesomeIcon
              icon={faAngleRight}
              tw="text-black text-sm cursor-pointer"
              onClick={() => onDilateItem(selectorItem)}
            />
          )}
        </div>
      </div>
    );
  };

  const handleFilterChange = (event: ChangeEvent<HTMLInputElement>) => {
    setFilterInput(event.target.value || "");  // Fallback to empty string if undefined or null
  };

  const handleFilterClearClicked = () => {
    setFilterInput("");
  };

  return (
    <div tw="relative overflow-hidden h-[400px] w-[224px] border-r border-component-dark-3">
      {isLoading ? (
        <div tw="flex items-center justify-center h-full w-full">
          <Spinner />
        </div>
      ) : items.length ? (
        <div tw="flex flex-col w-full h-full">
          <div tw="grow">
            <animated.div
              tw="absolute top-0 left-0"
              css={[tw`absolute h-full shadow-selector`]}
              id="test"
              style={springs}
            >
              <FixedSizeList
                height={355}
                width={defaultStyle.width}
                itemSize={46}
                itemCount={filteredList.length}
                overscanCount={3}
              >
                {/*
  // @ts-ignore */}
                {renderSelectorItem}
              </FixedSizeList>
            </animated.div>
          </div>
          <SelectorFilterInput
            value={filterInput}
            onChange={handleFilterChange}
            onClearClicked={handleFilterClearClicked}
          />
        </div>
      ) : (
        <div tw="flex items-center justify-center h-full w-full">
          <Text variant="noResult" tw="w-7/12 text-center">
            {emptyMessage}
          </Text>
        </div>
      )}
    </div>
  );
};

When i try to display on front-end the variavel “face_names” he always come empty

I have a facial recognition webapp in django, and I’m trying to show the user through a variable "face_names" which names are being captured on the screen, but it is always empty even when it has values ​​inside.

I’ve already tried just putting the value, you always have to search for a different value and it still didn’t work, I just wanted to show it in text form.

Views.py

class FaceRecognition: 
...
    def run_recognition(self, request, frame):
    ...
        response_data = {
        "face_names": face_names,
        }
        print("response_data:", response_data)
    
        # Vamos retornar esse dicionário.
        return JsonResponse (response_data)

HTML

<h1 class="titulo">Camera</h1>
<div id="error-message" style="display: none;">
<p>Error aaccessing Camera </p>
    </div>
    <video id="video" autoplay></video>
    <canvas id="canvas" width="640" height="480" style="display: none;"></canvas>
    <div id="processing-message" style="display: none;">Running</div>
    <div id="face-names"></div>
    
    <button id="capture-button" onclick="captureFrame()">Capture Frame</button>

JavaScript

function sendFrameToServer(blob) {
        showProcessingMessage();
        hideButton();
        const data = new FormData();
        data.append('frame_data', blob, 'frame.jpg');

        fetch('/processar_reconhecimento_facial/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken') // Adicione o token CSRF
            },
            body: data
        }).then(response => {
            if (response.ok) {
                // Se a resposta for bem-sucedida, capture o próximo frame
                console.log(response);
                captureFrame();
            }
            if (response.headers.get('Content-Type') === 'application/json') {
                console.log("json response");
                console.log(data);

                return response.json();
            } else {
                console.log("blob response");
                return response.blob();
            }
        })
        .then(data => {
            if (data.message === 'redirecionamento') {
                window.location.href = data.url;
            }
            if (data.face_names) {
                document.getElementById('face-names').innerText = data.face_names;
            } else {
                document.getElementById('face-names').innerText = 'Nome detectado: Nao sei porque nao deu certo';
                console.log('face_names is undefined');
                console.log('data:', data);
                console.log('face_names:', data.face_names);

            }
            showButton(); 
            hideProcessingMessage();
        })
        .catch(error => {
            console.error('Error sending frame to server:', error);
        });
    }

Logs

Django Termnial: response_data: {'face_names': ['andre']}

Web Console:

Response {type: 'basic', url: 'http://127.0.0.1:8000/processar_reconhecimento_facial/', redirected: false, status: 200, ok: true, …}
reconhecimento_facial/:79 json response
reconhecimento_facial/:80 FormData {}
reconhecimento_facial/:96 face_names is undefined
reconhecimento_facial/:97 data: {message: Array(0)}
reconhecimento_facial/:98 face_names: undefined

I’m getting redirected to Sign In page even after authentication using NextAuth.js

I’m using NextAuth for authentication and I’m using middleware to protect my routes. Whenever I visit the /contact page, I’m getting redirected to the /api/auth/signin page which is usual and expected behaviour. But when I’m authenticated, I’m still in the Sign In page. I checked my Network tab, where it showed that I was redirected back to /contact page followed by /api/auth/signin page.

Here’s my middleware.ts

// export { default } from 'next-auth/middleware'
import { NextRequest, NextResponse } from 'next/server'
import { withAuth } from 'next-auth/middleware'
import { getSession } from 'next-auth/react'

export default withAuth(
  function middleware(req: NextRequest) {
    console.log('middleware')
  },
  {
    callbacks: {
      authorized({ req, token }) {
        if (token) return true
      },
    },
  },
)

export const config = { matcher: ['/contact'] }

If I’m signing in, how do I get redirected to the /contact page and not get redirected to the sign in page again? And even if I’m visiting the Sign In page even after authentication, how do I get redirected to the default callback URL?

left and right arrows are missing in jquery datepicker to navigate months

I am trying to create a component to select date with jquery datepicker. I am able to navigate and functionality is working when i click, But i see left and right arrows are missing.

Here is code.

HTML:

<table border="0px" style="width: 100%; height: 50px;">
    <tr>
        <td style="width: 15%; font-weight: 600;">
            Product
        </td>
        <td style="width: 35%;">
            <select class="form-control rawfileproduct">
                <option value="0">Please Select</option>
            </select>
        </td>
        <td style="width: 15%; font-weight: 600;">
            Source Date
        </td>
        <td style="width: 35%;">
            <input type="text" class="rawfiledates_dp" name="date">
        </td>
    </tr>
</table>

JS code:

$(".rawfiledates_dp").datepicker({
        changeMonth: false,
        changeYear: true,
        maxDate: 0,
        beforeShowDay: function(date) {
          var dateString = $.datepicker.formatDate('yy-mm-dd', date);
          if (allowedDates.includes(dateString)) {
            return [true, 'ui-state-highlight', ''];
          }
          return [false, '', ''];
        }
});

            

CSS Code:

.ui-datepicker-calendar > tbody > tr > td:hover {
 background-color: lightgreen;
 border-radius: 50%;
}

.ui-datepicker-calendar > tbody > tr > td
{
    text-align: center;
}

Sample Image:
enter image description here
Please help me, Thanks.

Konva animation iteration counter to stop animation after 1

I wanted to animate the yellowLine to flow one time from left to tight across the screen. After that it should stay solid.
The added animation works as it should but the yellowLine gets shortened.
Is there a different approach to the anim.stop(), like an iteration counter?

<div class="content-container">
  <div id="stage">
    <div style="position: relative; user-select: none; width: 1425px; height: 392.5px;" class="konvajs-content" role="presentation"><canvas style="padding: 0px; margin: 0px; border: 0px none; background: transparent; position: absolute; top: 0px; left: 0px; width: 1425px; height: 392.5px; display: block;" width="1425" height="392"></canvas></div>
  </div>
</div>
<script src="https://unpkg.com/konva@9/konva.min.js"></script>
const stage = new Konva.Stage({
  width: window.innerWidth,
  height: document.querySelector('.content-container').clientHeight / 2,
  container: 'stage',
});

const layer = new Konva.Layer();

const bluePoly = new Konva.Line({
  points: [0, 0, stage.width(), 0, stage.width() / 2, stage.height() / 2, 0, stage.height() / 2],
  fill: '#3769cd',
  closed: true,
});

const whitePoly = new Konva.Line({
  points: [0, 0, stage.width() / 2, 0, (stage.width() / 2) * 1.5, stage.height() / 2, 0, stage.height() / 2],
  fill: '#ffffff',
  closed: true,
  x: 0,
  y: stage.height() / 2,
});

const yellowLine = new Konva.Line({
  points: [0, 0, stage.width() / 2, 0, ((stage.width() / 2) * 1.5) - 50, (stage.height() / 2) - 20, stage.width(), (stage.height() / 2) - 20],
  stroke: 'yellow',
  strokeWidth: 10,
  x: 0,
  y: stage.height() / 2,
  dash: [stage.width(), stage.width()],
  dashOffset: stage.width(),
});

const anim = new Konva.Animation(function(frame) {
  yellowLine.dashOffset(stage.width() - (frame.time * stage.width() / 2055));
}, layer);

anim.start();

setTimeout(function() {
  anim.stop();
  redrawYellowLine();
}, 2055);

const redrawYellowLine = () => {
  const viewportWidth = stage.width();
  const viewportHeight = stage.height();

  yellowLine.points([0, 0, viewportWidth / 2, 0, ((viewportWidth / 2) * 1.5) - 50, (viewportHeight / 2) - 20, viewportWidth, (viewportHeight / 2) - 20]);
  layer.batchDraw();
};

layer.add(bluePoly, whitePoly, yellowLine);
stage.add(layer);

window.addEventListener('resize', () => {
  stage.width(window.innerWidth);
  stage.height(document.querySelector('.content-container').clientHeight / 2);

  const viewportWidth = stage.width();
  const viewportHeight = stage.height();

  bluePoly.points([0, 0, viewportWidth, 0, viewportWidth / 2, viewportHeight / 2, 0, viewportHeight / 2]);
  whitePoly.points([0, 0, viewportWidth / 2, 0, (viewportWidth / 2) * 1.5, viewportHeight / 2, 0, viewportHeight / 2]);
  yellowLine.points([0, 0, viewportWidth / 2, 0, ((viewportWidth / 2) * 1.5) - 50, (viewportHeight / 2) - 20, viewportWidth, (viewportHeight / 2) - 20]);

  redrawYellowLine();
  layer.batchDraw();
});

encountering issues with lazyloading webworker code

I have 4 JS files(one.js, two.js, three.js and four.js). One.js imports two.js, two.js imports three.js and three.js import four.js using importScripts as a webworker code. How do I lazyload these files to retain the webworker functionality.

I am facing importScripts is not defined error, when I try to achieve the same and in this case should I lazyload all the files?

chrome.runtime.onMessage.addListener() getting triggered multiple times

The chrome.runtime.onMessage.addListener() function is being invoked once for the first message received, but subsequently, it’s being invoked multiple times, increasing with each subsequent message. An example for the issue is in the this image –
click here to view the image

The extension targets a specific Chrome tab playing a local video file, with actions intended solely for that tab.

The code that’s causing the issue:

content.js

// content.js
console.log("--- Start of Content.js --");

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

    console.log("Entered onMessage.addListener")
    var video = document.querySelector("video");
    
    if (!video) return;

    switch (request.action) {
        case "play":
            video.play();
            break;
        case "pause":
            video.pause();
            break;
        case "forward":
            video.currentTime += 5;
            break;
        case "backward":
            video.currentTime -= 5;
            break;
    }
});

background.js

// background.js
console.log("Background.js");

const urlTest = 'https://api-endpoint.com/get';

function checkAndDoAction() {
    fetch(urlTest)
        .then(response => response.text())
        .then(data => {
            if (data !== "None") {

                const action_ = data.trim();
                
                queryInfo = {'url': 'file:///Users/username/*'};

                chrome.tabs.query(queryInfo, function(tabs) {
                    chrome.scripting.executeScript({
                        target: { tabId: tabs[0].id },
                        files: ["content.js"]
                    }).then(() => {
                        console.log("sending msg to content" )
                        chrome.tabs.sendMessage(tabs[0].id, { action: action_ });
                    }).catch((error) => {
                        console.error("Error executing script:", error);
                    });
                });

            }
        })
        .catch(error => console.error("Error:", error));
}

setInterval(checkAndDoAction, 500);

manifest.json

{
    "manifest_version": 3,
    "name": "Video Controller - extension",
    "version": "4.0",
    "description": "Browser extension to control video playback.",
    "permissions": ["scripting", "tabs", "storage" ],
    "host_permissions": ["file:///Users/username/*"],
    "action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "icons/playback-16.png",
        "48": "icons/playback-48.png",
        "128": "icons/playback-128.png"
      }
    },
    "icons": {
      "16": "icons/playback-16.png",
      "48": "icons/playback-48.png",
      "128": "icons/playback-128.png"
    },
    "background": {
      "service_worker": "background.js"
    },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["content.js"]
      }
    ]
  }

I tried asking chatgpt, refering multiple forums and non of them worked. I need to figure out a way to make sure the function gets triggered only once every call.

prevent the browser tab from closing in javascript

I want to prevent the tab from closing using the onbeforeunload event by doing this:

window.onbeforeunload = function () {
    return confirm("Are you sure you want to go out?")
}

But it works only when reloading the page in the tab, or when trying to follow a link, but not when closing the tab.

Can anyone help me figure this out? Thanks!