useScriptTriggerConsent()
Load a script when a resolvable consent value grants permission or you call accept(). The revoke() method updates the reactive consent state; it does not unload a script that has already loaded or cancel a postConsentTrigger that started after acceptance.
A Promise<void> grants consent when it resolves.
Signature
function useScriptTriggerConsent(options?: ConsentScriptTriggerOptions): UseConsentScriptTriggerApi
Arguments
export interface ConsentScriptTriggerOptions {
/**
* An optional reactive (or promise) reference to the consent state. You can use this to accept the consent for scripts
* instead of using the accept() method.
*/
consent?: Promise<boolean | void> | Ref<boolean> | ComputedRef<boolean> | boolean
/**
* An optional condition to wait for after consent. `onNuxtReady`, a
* promise-returning function, and callback-style trigger functions are supported.
*/
postConsentTrigger?: ExcludePromises<NuxtUseScriptOptions['trigger']> | (() => Promise<any>)
}
At runtime, postConsentTrigger supports 'onNuxtReady', a callback-style function that accepts resolve, or a zero-argument function that returns a promise. A synchronous zero-argument function never resolves the trigger, even though the wider option type can admit one.
During SSR, the composable returns an unresolved promise with no-op accept() and revoke() methods. Consent can only release the load gate in the browser.
Returns
An extended promise with methods to accept and revoke consent.
interface UseConsentScriptTriggerApi extends Promise<void> {
/**
* A function that can be called to accept the consent and load the script.
*/
accept: () => void
/**
* Revoke consent by setting `consented` to false. This does not unload an
* already-loaded script.
*/
revoke: () => void
/**
* Reactive reference to the consent state.
*/
consented: Ref<boolean>
}
Examples
Basic Usage
<script setup lang="ts">
const trigger = useScriptTriggerConsent()
useScript('https://example.com/script.js', { trigger })
</script>
<template>
<div v-if="trigger.consented.value">
<p>Cookies accepted</p>
<button @click="trigger.revoke">
Revoke Consent
</button>
</div>
<button v-else @click="trigger.accept">
Accept Consent
</button>
</template>