问题描述
我正在尝试实现Google指南中的“自定义Google登录按钮”示例,但它甚至没有调用回调。如果我使用纯HTML和Javascript,则可以使用,但不能在svelte中使用:
CustomGoogleSignInButton.svelte
<script>
function onSuccess(googleUser) {
console.log("Logged in as: " + googleUser.getBasicProfile().getName());
}
function onFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render("my-signin2",{
scope: "profile email",width: 240,height: 50,longtitle: true,theme: "dark",onsuccess: onSuccess,onfailure: onFailure
});
}
</script>
<svelte:head>
<script
src="https://apis.google.com/js/platform.js?onload=renderButton"
async
defer>
</script>
</svelte:head>
<div id="my-signin2" />
解决方法
onload=renderButton
的意思是“在加载该脚本时,调用名为renderButton
的 global 函数。在您的<script>
块中声明的函数对于组件来说是 local ,因此没有全局renderButton
。
您可以通过将函数添加到窗口对象中来解决它...
window.renderButton = function() {
gapi.signin2.render("my-signin2",{
scope: "profile email",width: 240,height: 50,longtitle: true,theme: "dark",onsuccess: onSuccess,onfailure: onFailure
});
}
...但是您也可以像下面这样使用本地函数:
<svelte:head>
<script
src="https://apis.google.com/js/platform.js"
on:load={renderButton}
async
defer>
</script>
</svelte:head>
如果可行,则最好污染window
对象。