When I run this code in my localhost server and I click the Show Ad button in the #!/reward page, the reward ad shows but sends me back to the #!/ page. However, in this online code editor this SPA (single page app) works as intended: it plays the ad but leaves you on the reward page. Obviously this must have something to do with the fact that the application is running in an iframe on the editor, but why am I getting the "unexpected" behavior on my localhost and "expected" behavior in these online editors (I've also tested in jsbin and jsfiddle and same result).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
</script>
</head>
<body>
<div id="App"></div>
<script src="https://unpkg.com/mithril/mithril.min.js"></script>
<script>
window.googletag = window.googletag || {cmd: []};
googletag.cmd.push(() => {
googletag.enableServices();
googletag.pubads().addEventListener('rewardedSlotReady', event => event.makeRewardedVisible());
googletag.pubads().addEventListener('rewardedSlotClosed', event => googletag.destroySlots([event.slot]));
});
const Home = {
view: () => m('button', {
onclick: () => m.route.set('/reward')
}, 'Go to Reward Page >>>')
}
const Reward = {
view: () => [
m('button', {
onclick: () => m.route.set('/')
}, '<<< Return to Home Page'),
m('button', {
onclick: () => googletag.cmd.push(() => {
const rewardedSlot = googletag.defineOutOfPageSlot('/22639388115/rewarded_web_example', googletag.enums.OutOfPageFormat.REWARDED);
if(rewardedSlot)
{
rewardedSlot.addService(googletag.pubads());
googletag.display(rewardedSlot);
}
})
}, 'Show Ad')
],
}
m.route(document.getElementById('App'), '/', {
'/': Home,
'/reward': Reward
});
</script>
</body>
</html>
UPDATE (2022.08.03 11:16)
I can confirm that by placing this code into a subdirectory and then running it inside an iframe I get the expected behavior. I still need to understand why it doesn't work without the iframe. Here's a Glitch page that illustrates both scenarios. Click the View button on the preview pane to view it in its own window and note the difference.
The specific code for a rewarded ad appends #goog_rewarded to the end of the page's URL. This is what forces the unexpected behaviour to return to the default route of Mithril's router when using the default #! strategy. The added # triggers a hashchange
event and Mithril cannot resolve the route. Setting the m.route.prefix
to a different strategy (in my case m.route.prefix = '?'
) resolves the problem as it prevents the lookup from taking place.