From 29a8c9a53caac86d2b44314e62cd515caf02e236 Mon Sep 17 00:00:00 2001 From: AdamSGit Date: Fri, 8 Apr 2022 10:14:46 +0200 Subject: [PATCH] [feature/crossorigin] Add crossorigin attribute support This PR : - Add an option to set crossorigin attribute - Pass the option to `loadScript` method - Update the readme to reflect this change --- README.md | 6 +++++- src/index.js | 5 +++-- src/utils.js | 6 +++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 518502c..1859441 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,11 @@ Vue.use(VueMatomo, { // return null // } // } - trackSiteSearch: false + trackSiteSearch: false, + + // Set this to include crossorigin attribute on the matomo script import + // Default: undefined, possible values : 'anonymous', 'use-credentials' + crossOrigin: undefined, }); // Now you can access piwik api in components through diff --git a/src/index.js b/src/index.js index 328be13..0f41516 100644 --- a/src/index.js +++ b/src/index.js @@ -16,7 +16,8 @@ const defaultOptions = { userId: undefined, cookieDomain: undefined, domains: undefined, - preInitActions: [] + preInitActions: [], + crossOrigin: undefined } export const matomoKey = 'Matomo' @@ -180,7 +181,7 @@ export default function install (Vue, setupOptions = {}) { options.preInitActions.forEach((action) => window._paq.push(action)) - loadScript(trackerScript) + loadScript(trackerScript, options.crossOrigin) .then(() => piwikExists()) .then(() => initMatomo(Vue, options)) .catch((error) => { diff --git a/src/utils.js b/src/utils.js index ada202d..464ab3d 100644 --- a/src/utils.js +++ b/src/utils.js @@ -2,13 +2,17 @@ export function getMatomo () { return window.Piwik.getAsyncTracker() } -export function loadScript (trackerScript) { +export function loadScript (trackerScript, crossOrigin = undefined) { return new Promise((resolve, reject) => { const script = document.createElement('script') script.async = true script.defer = true script.src = trackerScript + if (crossOrigin && ['anonymous', 'use-credentials'].includes(crossOrigin)) { + script.crossOrigin = crossOrigin + } + const head = document.head || document.getElementsByTagName('head')[0] head.appendChild(script)