-
Notifications
You must be signed in to change notification settings - Fork 24
Custom Events
The ads you display on your page are confined to the provided slots, usually inside an iframe element.
Sometimes, however, it is desirable to be able to control the layout of the whole page for advertising. A common use case, for example, is setting the page background color to match that of an ad creative.
This can be done by dispatching a message from the iframe delivered by the ad server to the parent page using the browser's postMessage API, as described in this blog post.
React-advertising allows use to set up these custom events in your config and then pass a callback function to the AdvertisingSlot component as customEventHandlers prop.
Let's configure a custom event for changing the background color, for example, by adding this to the ad config:
const config = {
slots: [
{
id: "my-ad-id",
},
],
customEvents: {
blueBackground: {
eventMessagePrefix: "BlueBackground:",
},
},
};
We then pass this config to an AdvertisingProvider component and pass the callback to change the page background to an ad slot:
class App extends Component {
constructor(props) {
super(props);
this.state = {
backgroundColor: "red",
};
}
render() {
return (
<AdvertisingProvider config={config}>
<div style={{ backgroundColor: this.state.backgroundColor }}>
<AdvertisingSlot
id="my-ad-id"
customEvents={{
blueBackground: () => this.setState({ backgroundColor: "blue" }),
}}
/>
</div>
</AdvertisingProvider>
);
}
}
Note that you don't pass the callback function that sets the background color directly to the AdvertisingSlot, but rather as an object, where the key corresponds to the key of the custom event in the config (i.e. blueBackground).
You can even pass more than just one callbacks if need be.
With the setup above in place, you can then add a script snippet to the Google tag code delivered by the Ad Manager that changes the background color when the ad is served:
<script>
parent.postMessage("BlueBackground:my-ad-id", "*");
</script>
- The first parameter for postMessage consists of
- the custom event message prefix you have configured
- the ID of the ad
- The second parameter is the target origin, an asterix as in the example above should be sufficient in most cases (refer to postMessage documentation for details)
When the ad is now delivered from the ad server, the background color of the wrapper div in the App component turns from red to blue.
← Configuration | Plugins →