我遵循 Google 提供的指南來集成新的 Google 登錄。我使用 Google 提供的代碼生成器創(chuàng)建了 HTML。
這里我附上了完整的代碼
<svelte:head> <title>Home</title> <meta name="description" content="Svelte demo app" /> </svelte:head> <section> <div class="h-screen"> <div id="g_id_onload" data-client_id="534101779287-bm07dc8v4ln4kulqbql61nsglcku74vg.apps.googleusercontent.com" data-context="use" data-ux_mode="redirect" data-login_uri="http://localhost:5173/auth/callback" /> <div class="bg-red-300 h-80"> <div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signin_with" data-size="medium" data-logo_alignment="left" data-width="180" /> </div> </div> </section>
第一次渲染頁面時(shí)效果很好。
當(dāng)我們使用 Command R
或單擊瀏覽器中的重新加載圖標(biāo)刷新頁面時(shí),登錄按鈕消失。
現(xiàn)在我使用 Javascript 創(chuàng)建了組件,在這里我添加了答案。
我在 app.d.ts
中將 google 聲明為全局變量
// See https://kit.svelte.dev/docs/types#app // for information about these interfaces declare global { const google: any; namespace App { } } export {};
我創(chuàng)建了一個(gè) svelte 文件來創(chuàng)建用于登錄按鈕的 svelte 組件
let canvas: any; //Created a variable to optain a reference to rendered div element在 onMount 中
onMount(async () => { google.accounts.id.initialize({ client_id: "534101779287-bm07dc8v4ln4kulqbql61nsglcku74vg.apps.googleusercontent.com", ux_mode: "redirect", context: "use", login_uri: "http://localhost:5173/auth/callback" }); google.accounts.id.renderButton(canvas, { width: '220', theme: 'outline', size: 'large', type: 'standard', text: 'signin_with', shape: 'rectangular', logo_alignment: 'left', }); });此代碼將在初始渲染、硬重新加載 (Command+shift+R) 和重新加載 (Command+R) 中工作
使用 SvelteKit 時(shí),硬重新加載是在服務(wù)器端呈現(xiàn)的。代碼可能與此不兼容或者執(zhí)行順序錯(cuò)誤。
檢查控制臺(tái)是否有錯(cuò)誤,并將必須在客戶端上運(yùn)行的代碼移至 onMount
.您還可以使用 ssr
頁面選項(xiàng) 關(guān)閉特定頁面的服務(wù)器端渲染作為最后的手段。