0

我有一个旧的 Chrome 扩展程序,它向带有文件上传的站点添加了拖放功能。该站点在一个子域上有页面(例如:https : //foo.site.com/page1.php、https://foo.site.com/page2.php ..),而上传端点位于另一个子域(例如:https ://bar.site.com/upload.php )。从某些以前的 Chrome 版本开始,由于更严格的 CORS 规则,该扩展程序停止工作。上传文件的 POST 似乎成功了,但是响应因 CORB 错误而被阻止,我需要响应才能知道文件的新远程路径在哪里。

根据 Google 的指南,我尝试通过将请求从内容脚本移动到后台脚本来进行重构。但是,我不知道如何使用后台脚本共享拖放到页面上的文件。这是一些示例代码:

内容.js:

var setupDragAndDrop = function () {
  (
    document.getElementById("some_element")
  ).addEventListener("drop", function (e) {
    for (var t = 0, s = e.dataTransfer.files.length; t < s; t++)
      upload(e.dataTransfer.files[t], function (e) {
        insertResponseOnPage(e); // Use the upload response to show the new remote path on the page
      });
    e.preventDefault();
  });
},

var upload = function(file, callback) {
  chrome.runtime.sendMessage(
    {
      need: "upload",
      file: file,
      callback: callback
    }
  );
}

background.js(还有一些其他的逻辑可以让消息以这个方法结束,但它确实以文件和回调结束):

var upload = function(file, callback) {
  var formData = new FormData();
  formData.append('file', file);

  const UPLOAD_URL = 'https://bar.site.com/upload.php';
  var xhr = new XMLHttpRequest();
  xhr.open('POST', UPLOAD_URL, true);
  xhr.withCredentials = "true";

  xhr.onload = callback;

  xhr.send(formData);
};

我看到的这个问题是file背景页面上的结尾是一个空对象。我相信我在某处读到,使用消息 API 发送的任何内容都需要是 JSON 可序列化的,所以我假设File不是?如果我也尝试发送FormData对象,我也会得到相同的行为。我也尝试过以某种方式获取文件路径并在后台页面中重新创建文件的路线,但显然出于安全原因,您无法从 JS 中的系统文件中获取路径。

有没有办法修复这个扩展?我不拥有此扩展程序尝试添加功能的站点,因此我无法将上传端点移动到同一个子域。

4

0 回答 0