Unable to intract with YouTube opened in popup from chrome extension due to cross site error

Viewed 126

I have a chrome extension that gets the currently playing YouTube video object from a popup. Following are the steps I am following:

  1. User clicks the video link on our website. (SUCCESS)
  2. The website sends signal to extension to open the popup using internal messaging.(SUCCESS)
  3. The YouTube popup opens and one other popup opens that redirects to a blank page hosted on our website.(SUCCESS)
  4. The blank page is injected with a script hosted inside the extension.(SUCCESS)
  5. This script fetches the YouTube video from other popup. (FAILED: CROSS SITE ACCESS ERROR)

I saw many extensions asking for user permission before accessing other domain sites. I tried this method:

When user clicks a video link on our website it executes this function:

function go() 
   {
   var event = document.createEvent('Event');
   event.initEvent('openmyapp');
   document.dispatchEvent(event);
   }

The content script of the extension listen to this event as follows:

document.addEventListener("openmyapp", function (data) {
    if (cscript)
        cscript.injectApp();    // <-- This is successfully injecting the app.
    (window.browser || window.chrome).runtime.sendMessage(extensionId, 'site_pop',
        function (granted) {
            console.log(granted);
        });
});

The background script asks for permission:

browser.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    console.log(message);
    if (message == 'site_pop') {
        browser.permissions.request({
            origins: ["*://*.youtube.com/*"]
        }, async (granted) => {
                console.log(granted);
        });
    }
});

It is opening the YouTube and app popup but not asking for permission.

How can I solve this?

1 Answers

you may need to modify response headers, if using iframe remove X-Frame-Options and if using XHR add Access-Control-Allow-Origin: *

// manifest.json

"permissions": [
  "webRequest", "webRequestBlocking", ".*://*.youtube.com/*"
]

// background.js
chrome.webRequest.onHeadersReceived.addListener(
  function(details) {
    let newHeaders = {};

    for (let key in details.responseHeaders) {
      if (key.toLowerCase() == 'x-frame-options')
        continue;
      newHeaders[key] = details.responseHeader[key]
    }
    
    // add xhr permission
    newHeaders['Access-Control-Allow-Origin'] = '*';

    return { newHeaders };
  },
  // filters
  {
    urls: ["*://*.youtube.com/*"],
  },
  // extraInfoSpec
  ["blocking", "responseHeaders"]
);
Related