简体   繁体   English

需要帮助在网页上显示异步 function 的结果

[英]Need help displaying the result of an asynchronous function on a webpage

I am trying to use the Spotify PKCE authorization with Siri Shortcuts.我正在尝试将 Spotify PKCE 授权与 Siri Shortcuts 一起使用。 Unfortunately, none of the solutions I have found have been applicable to my specific situation.不幸的是,我找到的解决方案都不适用于我的具体情况。 I have this bit of code And I really have no idea what I am doing.我有这段代码而且我真的不知道我在做什么。 Basically I need a SHA256 hash of a string of characters, but this needs to be by bytes vs the hex.基本上我需要一个字符串的 SHA256 hash ,但这需要字节与十六进制。 This then needs to be base64Url encoded.然后需要对其进行 base64Url 编码。 I've have tried most of the solutions on stack but I can't seem to output the final product onto a webpage, which is the main way I am able to run Java script natively on iPhone.我已经在堆栈上尝试了大多数解决方案,但我似乎无法将最终产品 output 放到网页上,这是我能够在 iPhone 上本地运行 Java 脚本的主要方式。 Any help would be greatly appreciated任何帮助将不胜感激

<script>

    function sha256(plain) { 
        // returns promise ArrayBuffer
        const encoder = new TextEncoder();
        const data = encoder.encode(plain);
        return window.crypto.subtle.digest('SHA-256', data);
    }

    function base64urlencode(a) {
        // Convert the ArrayBuffer to string using Uint8 array.
        // btoa takes chars from 0-255 and base64 encodes.
        // Then convert the base64 encoded to base64url encoded.
        // (replace + with -, replace / with _, trim trailing =)
        return btoa(String.fromCharCode.apply(null, new Uint8Array(a)))
            .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    }

    async function pkce_challenge_from_verifier(v) {
        hashed = await sha256(v);
        base64encoded = base64urlencode(hashed);
        return base64encoded;
    }

const code = await pkce_challenge_from_verifier("Zg6klgrnixQJ629GsawRMV8MjWvwRAr-vyvP1MHnB6X8WKZN")

document.getElementById("value").innerHTML =  code;

</script>
<body>

<p id="value"></p>
</body>
</html> ```

await is not allowed at global level ie you can use await only inside async functions.全局级别不允许使用await ,即您只能在async函数中使用await So how to solve?那么如何解决呢? use promise instead of await .使用 promise 而不是await like this像这样

pkce_challenge_from_verifier("Zg6klgrnixQJ629GsawRMV8MjWvwRAr-vyvP1MHnB6X8WKZN")
  .then((code) => document.getElementById("value").innerHTML = code)
  .catch((error) => console.error(error))

also place <script>... </script> after body end tag otherwise JS cant find p element.还要将<script>... </script>放在body结束标记之后,否则 JS 无法找到p元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM