Files
progcode/docs/metrika/browser-real-sdk.js
T
2026-10-27 03:59:37 +03:00

20 lines
2.5 KiB
JavaScript

async page => {
const context=page.context(),requests=[],errors=[],violations=[];
const sdkResponse=await context.request.get('https://mc.yandex.ru/metrika/tag.js');
if(sdkResponse.status()!==200)throw Error('SDK HTTP '+sdkResponse.status());
const sdk=await sdkResponse.text();
await context.route('**/*',async route=>{const url=route.request().url();if(url.startsWith('https://progcode.ru/')){const r=await context.request.get(url.replace('https://progcode.ru','http://127.0.0.1:51555'));await route.fulfill({response:r});}else if(url==='https://mc.yandex.ru/metrika/tag.js'){await route.fulfill({body:sdk,contentType:'application/javascript'});}else{const data=url+' '+(route.request().postData()||'');requests.push({endpoint:url.split('?')[0],method:route.request().method(),goalSearch:data.includes('search_used'),goalZero:data.includes('search_zero_results'),containsTestQuery:data.includes('private%40example')||data.includes('private@example')});await route.fulfill({status:200,contentType:'application/json',body:'{}'});}});
page.on('pageerror',e=>errors.push(e.message));
await context.addInitScript(()=>document.addEventListener('securitypolicyviolation',e=>(window.__cspViolations??=[]).push(e.violatedDirective)));
await page.goto('https://progcode.ru/');await page.waitForTimeout(2000);
await page.locator('#search').fill('private@example.test');await page.waitForTimeout(1000);
await page.locator('#search').fill('jquery');await page.locator('.journal-list a').first().click();await page.waitForTimeout(1500);
if(!requests.some(x=>x.endpoint.includes('/watch/109268613')))throw Error('No real SDK watch request');
const goalsSerialized=requests.some(x=>x.goalZero)&&requests.some(x=>x.goalSearch);if(!goalsSerialized)throw Error('Real SDK goals not serialized');
if(requests.some(x=>x.containsTestQuery))throw Error('Raw search leaked');
if(errors.length)throw Error('SDK error '+errors.join(';'));
const csp=await page.evaluate(()=>window.__cspViolations||[]);if(csp.length)throw Error('CSP violations');
const sdkSHA256=await page.evaluate(async source=>[...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(source)))].map(v=>v.toString(16).padStart(2,'0')).join(''),sdk);
return {goalsSerialized,sdkSHA256,sdkHTTP:sdkResponse.status(),sdkBytes:sdk.length,sdkServedAsExternalAsyncScript:await page.locator('script[src="https://mc.yandex.ru/metrika/tag.js"]').evaluate(el=>el.async),requests,errors,cspViolations:csp,allStatisticsRequestsLocallyFulfilled:true,statisticsDelivered:0};
}