0

I'm trying to write code to hook the dcument.cookie (both write and read property) and the corresponding scripts and script URLs by using the call stack trace or error stack facility of javascript but I'm unable to get it, not sure what I'm doing wrong. Here's my piece of code. If anyone could help me, would be thankful. PS: I'm using playwright as a automation tool.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({headless: false});
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://www.microsoft.com');
  
  const callStackPromise = await page.evaluate(async () => {
    await new Promise(resolve => {
      window.onload = resolve;
    });

    console.log('Evaluating call stack...');

    const stack = new Error().stack.split('\n').slice(1).map(line => line.trim());
    console.log('Call stack:', stack);

    let scripts = Array.from(document.scripts).map(script => script.src);
    console.log('Scripts:', scripts);

    let cf = [];

    for (let i = 0; i < stack.length; i++) {
      let line = stack[i];
      let matches = line.match(/at (.*?) \(/);
      if (matches && matches[1].includes('document.cookie')) {
        let scriptUrl = scripts.find(scriptUrl => line.includes(scriptUrl));
        if (scriptUrl) {
          cf.push({ url: scriptUrl });
        }
      }
    }

    console.log('Call stack result:', cf);

    return cf;
  });

  const callStack = await callStackPromise;

  console.log(callStack);


  await browser.close();
})();

ZA09
  • 71
  • 6
  • I'm not sure what you're trying to do here, but the `window.onload = resolve;` thing seems pretty odd. `page.goto` already waits for the load event to fire. `callStackPromise` is `await`ed twice. – ggorlen Apr 05 '23 at 17:09
  • Oh my bad. you are right. However, still have the same issue. I'm trying to hook the dcument.cookie (both write and read property) and the corresponding scripts and script URLs of the page by using the call stack trace or error stack facility of javascript – ZA09 Apr 05 '23 at 23:31
  • Why not use Playwright's [`page.cookies()`](https://playwright.dev/docs/api/class-browsercontext#browser-context-cookies) method? I'm not sure why you need the scripts exactly. This all seems [a bit odd](https://meta.stackexchange.com/a/233676/399876) to want to do. Are you testing something or...? – ggorlen Apr 06 '23 at 00:00
  • Actually I already did that. Now I want to catch/hook all the calls of `document.cookie` and corresponding scripts and scripts URL in the page to compare it with data I already collected for some analysis – ZA09 Apr 06 '23 at 09:22

0 Answers0