6

Overview

I was able to successfully inject my Javascript script through the new chrome.scripting API.

However, I am still unable to access the page's window object via this injected script.

What I have tried

Back in MV2 I used to do the following:

async function getWindow() {
    return new Promise(function (resolve, reject) {
      const script = document.createElement('script');
      script.text = `
            const _window = JSON.stringify(window);
            document.body.insertAdjacentHTML("beforebegin", "<div id='dummy' style='display:none;width:0;height:0;pointer-events:none;'>"+_window+"</div>")
        `;

      document.getElementsByTagName('head')[0].appendChild(script);

      const _window = document.getElementById('dummy');
      const data = JSON.parse(_window.innerText)

      script.remove();
      resolve(data);
    });
  }

 (async () => {
    const _window = await getWindow();
    console.log(_window)
  })();

But it's no longer possible. it gives me the following error:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-iAKY8pCLpBsSPttuizEMbuFVrucrXcGUoo/RYdGQEyw='), or a nonce ('nonce-...') is required to enable inline execution.

Based on that error I found this answer and this question answer, but it doesn't solve my problem since the former is for the MV2 and the latter is using an external script. I can't seen to make it work with a local script.

What I'm trying to achieve

I would like to access the window object of a given website from my Chrome Extension.

Other notes

  • In my manifest I have the following permissions:
  "permissions": ["scripting", "activeTab", "webRequest"]

Additionally, I have added my script under content_scripts and also web_accessible_resources.

Any help is greatly appreciated.

Thank you!

Diego Fortes
  • 8,830
  • 3
  • 32
  • 42
  • 1) Use a separate js file for the script element, 2) JSON.stringify(window) will fail due to circular references. 3) Example: [Access global js variables from js injected by a chrome extension](https://stackoverflow.com/a/46870005) – wOxxOm May 11 '21 at 04:08

0 Answers0