【问题标题】:Unable to intract with YouTube opened in popup from chrome extension due to cross site error由于跨站点错误,无法与从 chrome 扩展程序的弹出窗口中打开的 YouTube 交互
【发布时间】:2021-04-28 18:32:42
【问题描述】:

我有一个 chrome 扩展程序,可以从弹出窗口中获取当前正在播放的 YouTube 视频对象。以下是我正在遵循的步骤:

  1. 用户点击我们网站上的视频链接。 (成功)
  2. 网站向扩展程序发送信号以使用内部消息打开弹出窗口。(成功)
  3. YouTube 弹出窗口打开,另一个弹出窗口打开,重定向到我们网站上托管的空白页面。(成功)
  4. 空白页面被注入了一个托管在扩展中的脚本。(成功)
  5. 此脚本从其他弹出窗口获取 YouTube 视频。 (失败:跨站点访问错误)

我看到许多扩展程序在访问其他域站点之前要求用户许可。我试过这个方法:

当用户点击我们网站上的视频链接时,它会执行此功能:

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

扩展的内容脚本监听这个事件如下:

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);
        });
});

后台脚本请求权限:

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);
        });
    }
});

它正在打开 YouTube 和应用弹出窗口,但未请求许可。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript html google-chrome firefox google-chrome-extension


    【解决方案1】:

    您可能需要修改响应标头,如果使用 iframe,则删除 X-Frame-Options,如果使用 XHR,则添加 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"]
    );
    

    【讨论】:

    • Access-Control-Allow-Origin: * 作为响应头通常被认为是一个坏主意。我不知道如何允许扩展来做到这一点
    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多