MatteoGabriele / vue-gtag-next

Global Site Tag plugin for Vue 3 (gtag.js)
MIT License
44 stars 3 forks source link

Support for SSR: throwing error as 'window is not defined' #30

Open camilodelvasto opened 2 years ago

camilodelvasto commented 2 years ago

Description

Showing this error on SSR mode:

UnhandledPromiseRejectionWarning: ReferenceError: window is not defined
    at getTemplate

What are you reporting? It should identify that the window object is undefined

Actual behavior

Throwing error

Environment

Vue3/Vite using SSR and vue-gtag-next@1.14.0

Reproducible Demo

Creating a demo is a little difficult given that the SSR implementation varies, but it should be obvious from the code: the getTemplate function is assuming the window object exists, but this is not the case in SSR:

var getTemplate = function getTemplate() {
  var to = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var _useRouterState = useRouterState(),
      template = _useRouterState.template,
      useScreenview = _useRouterState.useScreenview;

  var customTemplate = template.value ? template.value(to, from) : null;

  if (customTemplate) {
    return customTemplate;
  } else if (useScreenview.value) {
    return {
      screen_name: to.name
    };
  } else {
    return {
      page_title: to.name,
      page_path: to.path,
      page_location: window.location.href
    };
  }
};