Skip to main content

🔷 TypeScript Integration

This guide provides a complete reference for using Magfi Ad Network SDK with TypeScript, including type definitions and usage examples.

Types

AdCallbacks

This type defines the structure for callback functions that can be provided when showing an ad.

type AdCallbacks = {
onClosed?: () => void;
onGranted?: () => void;
onSkip?: () => void
};

onClosed: An optional function that will be called when the ad is closed.

onGranted: An optional function that will be called when user grants necessary permissions (e.g., for personalized ads).

onSkip: An optional function that will be called when the user skips the rewarded ad without receiving the reward.


AdEventName

This type defines the possible event names that can be used with addEventListener and removeEventListener.

type AdEventName = "onReady" | "onGranted" | "onStart" | "onClose" | "onError" | "adNotFound" | "onSkip";

The possible event names are:

onReady: Triggered when the ad is ready to be shown.

onGranted: Triggered when user grants necessary permissions.

onStart: Triggered when the ad starts displaying.

onClose: Triggered when the ad is closed.

onError: Triggered if there is an error loading or displaying the ad.

adNotFound: Triggered when no ad is available to display.

onSkip: An optional function that will be called when the user skips the rewarded ad without receiving the reward.


AdInstance

This interface defines the methods available for interacting with an ad instance.

type AdInstance = {
show: (callbacks?: AdCallbacks) => void;
isReady: () => boolean;
addEventListener: (eventName?: AdEventName, callback?: () => void) => void;
removeEventListener: (eventName?: AdEventName, callback?: () => void) => void;
};

show(callbacks?: AdCallbacks): Displays the ad. The optional callbacks object can be provided to specify functions to be called when certain events occur (e.g., ad close).

isReady(): Returns a boolean indicating whether the ad is ready to be shown.

addEventListener(eventName?: AdEventName, callback?: () => void): Registers a listener function for a specific ad event.

removeEventListener(eventName?: AdEventName, callback?: () => void): Removes a previously registered listener function for a specific ad event.


Usage Example

const magfi = window.MagfiAdNetwork.getInstance("DEBUGGER");
const adInstance = magfi.add({ AD_CODE: "rewarded" });

if (adInstance.isReady()) {
adInstance.show({
onClosed: () => {
console.log("Ad closed.");
},
onGranted: () => {
console.log("Permissions granted.");
},
onSkip: () => {
console.log("Ad Skipped");
}
});
}

adInstance.addEventListener("onClose", () => {
console.log("Ad closed via event listener.");
});

// ... later ...

adInstance.removeEventListener("onClose", thePreviouslyAddedCallbackFunction);