diff --git a/CHANGELOG.md b/CHANGELOG.md index 1170afc06..b2ed4c65b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,12 +20,14 @@ The format is based on [Keep a Changelog], and this project adheres to [Semantic ### Fixed +- issue with `metrika-yandex-tag` redirect when it's used as a scriptlet [#472] - issue with `trusted-click-element` scriptlet when `delay` was used and the element was removed and added again before it was clicked [#391] [Unreleased]: https://github.com/AdguardTeam/Scriptlets/compare/v2.0.1...HEAD [#391]: https://github.com/AdguardTeam/Scriptlets/issues/391 [#468]: https://github.com/AdguardTeam/Scriptlets/issues/468 +[#472]: https://github.com/AdguardTeam/Scriptlets/issues/472 ## [v2.0.1] - 2024-11-13 diff --git a/src/redirects/metrika-yandex-tag.js b/src/redirects/metrika-yandex-tag.js index 46170d216..57d96bf3b 100644 --- a/src/redirects/metrika-yandex-tag.js +++ b/src/redirects/metrika-yandex-tag.js @@ -108,16 +108,19 @@ export function metrikaYandexTag(source) { destruct, }; - function ym(id, funcName, ...args) { - return api[funcName] && api[funcName](id, ...args); - } - function init(id) { // yaCounter object should provide api window[`yaCounter${id}`] = api; document.dispatchEvent(new Event(`yacounter${id}inited`)); } + function ym(id, funcName, ...args) { + if (funcName === 'init') { + return init(id); + } + return api[funcName] && api[funcName](id, ...args); + } + if (typeof window.ym === 'undefined') { window.ym = ym; ym.a = []; diff --git a/tests/redirects/metrika-yandex-tag.test.js b/tests/redirects/metrika-yandex-tag.test.js index fa2bae88e..f56b67674 100644 --- a/tests/redirects/metrika-yandex-tag.test.js +++ b/tests/redirects/metrika-yandex-tag.test.js @@ -42,6 +42,40 @@ test('API mocking test', (assert) => { clearGlobalProps(`yaCounter${counterId1}`, `yaCounter${counterId1}`); }); +test('Init mocking test - when it is used as a scriptlet', (assert) => { + let testPassed = false; + + evalWrapper(redirects.getRedirect(name).content); + + window.ym = window.ym || function YandexMetrika(...args) { + (window.ym.a = window.ym.a || []).push(...args); + }; + + const counterId = 28510826; + + window.ym(counterId, 'init', { + clickmap: true, + trackLinks: true, + accurateTrackBounce: true, + webvisor: true, + ecommerce: 'dataLayer', + }); + + try { + window.yaCounter28510826.reachGoal('login'); + testPassed = true; + } catch (error) { + // eslint-disable-next-line no-console + console.error(`yaCounter${counterId} is not defined:`, error); + } + + assert.ok(window.ym, 'Metrika function was created'); + assert.ok(typeof window[`yaCounter${counterId}`] === 'object', 'yaCounter was created'); + assert.strictEqual(testPassed, true, 'testPassed is true'); + + clearGlobalProps(`yaCounter${counterId}`); +}); + test('ym: API methods test', (assert) => { assert.expect(4);