# OnBrowser Hook

The OnBrowser hook is executed during the rendering process, right before we initialize a Provider. This way the OnBrowser hook will have access to the Window (opens new window) object of the page.

AMP compatibility

On Browser middleware do not run on AMP pages.

Like the OnExtraction hook, it returns an object that will be used as parameters in a Provider.

WARNING

It's forbidden to use OnBrowser to access the DOM of the page. For that purpose use the OnExtraction Hook instead.

Use the OnBrowser hook to:

  • Provide custom key/values from DFP.
  • Change the configuration depending on geo or device type.
  • Send the current document.referrer as a custom dimension.
  • Create complex advertisement configurations that need JavaScript execution.

# Usage Examples

We can use it to pass information about the current page to our tracking pixel:

// on-browser.ts
import { FacebookPixelProps } from '@marfeel/analytics-providers-facebookpixel';
import { onBrowserFunction } from '@marfeel/middlewares-types';

export const onBrowser: onBrowserFunction<FacebookPixelProps> = async({ window }): Promise<FacebookPixelProps> => {
  return {
    extraUrlParams: {
      dl: window.location.href,
      rl: window.document.referrer
    }
  };
};

In this example, we define the hook by exporting a function that has the signature of onBrowserFunction.Then we access the Window object, which is provided as an argument, and return its data in the format defined by the Facebook Pixel Analytics Provider (opens new window).

For Ad Server works pretty similar. For example, we can send a tageting with the current page url to DFP.

// on-browser.ts
import { Config } from '@marfeel/adserver-providers-doubleclick';
import { onBrowserFunction } from '@marfeel/middlewares-types';

export const onBrowser: onBrowserFunction<Partial<Config>> = async({ window }): Promise<Partial<Config>> => {
    return {
        json: {
            targeting: {
                url: window.location.href
            }
        }
    };
};

In this case, we only return one of the parameters defined by the Doubleclick Ad Server Provider (opens new window), since we don't need to modify the others. So we need to specify that we will return the Config object as Partial (opens new window).

TIP

Every Middleware needs a test. Check the how to create test for middleware article to learn more.