【问题标题】:chrome.downloads.download API saveAs dialogue is flashing on the screen and then closes before i see the dialoguechrome.downloads.download API saveAs 对话框在屏幕上闪烁,然后在我看到对话框之前关闭
【发布时间】:2014-01-09 07:27:00
【问题描述】:

我正在开发 chrome 扩展,我想为可下载文件设置下载位置。所以我正在使用 chrome.downloads.download API saveAs:true。它在 Windows 操作系统中工作正常,但在 Mac OS 中,saveAs 弹出窗口在屏幕上闪烁,然后扩展弹出窗口和 saveAs 对话框在我看到它们之前关闭。

有什么想法吗?

我更新的代码:

ma​​nifest.json

{
  "name": "Download Selected Links",
  "description": "Select links on a page and download them.",
  "version": "0.1",
  "minimum_chrome_version": "16.0.884",
  "permissions": ["downloads", "<all_urls>"],
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {"default_popup": "popup.html"},
  "manifest_version": 2
}

popup.js

var allLinks = [];
var visibleLinks = [];
var filename = [];
var count = 0;

// Display all visible links.
function showLinks() {
  var linksTable = document.getElementById('links');
  while (linksTable.children.length > 1) {
    linksTable.removeChild(linksTable.children[linksTable.children.length - 1])
  }
  for (var i = 0; i < visibleLinks.length; ++i) {
    var row = document.createElement('tr');
    var col0 = document.createElement('td');
    var col1 = document.createElement('td');
    var checkbox = document.createElement('input');
    checkbox.checked = true;
    checkbox.type = 'checkbox';
    checkbox.id = 'check' + i;
    col0.appendChild(checkbox);
    col1.innerText = visibleLinks[i];
    col1.style.whiteSpace = 'nowrap';
    col1.onclick = function() {
      checkbox.checked = !checkbox.checked;
    }
    row.appendChild(col0);
    row.appendChild(col1);
    linksTable.appendChild(row);
  }
}

function toggleAll() {
  var checked = document.getElementById('toggle_all').checked;
  for (var i = 0; i < visibleLinks.length; ++i) {
    document.getElementById('check' + i).checked = checked;
  }
}

function  downloadLinks() {
var urlArray = new Array();
  for (var i = 0; i < visibleLinks.length; ++i) {
    if (document.getElementById('check' + i).checked) {
      urlArray.push(visibleLinks[i]);
    }
  }
  var zip = new JSZip();
  downloadFile(urlArray[count], onDownloadComplete, urlArray, zip);
}

// Re-filter allLinks into visibleLinks and reshow visibleLinks.
function filterLinks() {
  var filterValue = document.getElementById('filter').value;
  if (document.getElementById('regex').checked) {
    visibleLinks = allLinks.filter(function(link) {
      return link.match(filterValue);
    });
  } else {
    var terms = filterValue.split(' ');
    visibleLinks = allLinks.filter(function(link) {
      for (var termI = 0; termI < terms.length; ++termI) {
        var term = terms[termI];
        if (term.length != 0) {
          var expected = (term[0] != '-');
          if (!expected) {
            term = term.substr(1);
            if (term.length == 0) {
              continue;
            }
          }
          var found = (-1 !== link.indexOf(term));
          if (found != expected) {
            return false;
          }
        }
      }
      return true;
    });
  }
  showLinks();
}

chrome.runtime.onMessage.addListener(function(links) {
  for (var index in links) {
    allLinks.push(links[index]);
  }
  allLinks.sort();
  visibleLinks = allLinks;
  showLinks();
});

window.onload = function() {
  document.getElementById('filter').onkeyup = filterLinks;
  document.getElementById('regex').onchange = filterLinks;
  document.getElementById('toggle_all').onchange = toggleAll;
  document.getElementById('downloadButtonId').onclick = downloadLinks;

  chrome.windows.getCurrent(function (currentWindow) {
    chrome.tabs.query({active: true, windowId: currentWindow.id},
                      function(activeTabs) {
      chrome.tabs.executeScript(
        activeTabs[0].id, {file: 'source.js', allFrames: true});
    });
  });
};

source.js

var links = [].slice.apply(document.getElementsByTagName('a'));
links = links.map(function(element) {
  var href = element.href;
  var hashIndex = href.indexOf('#');
  if (hashIndex >= 0) {
    href = href.substr(0, hashIndex);
  }
  return href;
});

links.sort();

// Remove duplicates and invalid URLs.
var kBadPrefix = 'javascript';
for (var i = 0; i < links.length;) {
  if (((i > 0) && (links[i] == links[i - 1])) ||
      (links[i] == '') ||
      (kBadPrefix == links[i].toLowerCase().substr(0, kBadPrefix.length))) {
    links.splice(i, 1);
  } else {
    ++i;
  }
}

chrome.runtime.sendMessage(links);

background.js

function downloadFile(url, onSuccess, arrayOfUrl, zip) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = "blob";
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (onSuccess) {
        onDownloadComplete(xhr.response, arrayOfUrl, zip);
      }
    }
  }
  xhr.send(null);
}

function onDownloadComplete(blobData, urls, zip){
  if (count < urls.length) {
    blobToBase64(blobData, function(binaryData){
      // add downloaded file to zip:
      var fileName = urls[count].substring(urls[count].lastIndexOf('/')+1);
      // zip.file(fileName, binaryData, {base64: true});
      zip.file(fileName+".docx", binaryData, {base64: true}); //file"+count+".docx"
      if (count < urls.length -1){
        count++;
        downloadFile(urls[count], onDownloadComplete, urls, zip);
      } else {
        chrome.runtime.getBackgroundPage(function () {
          zipAndSaveFiles(zip);
        });
      }
    });
  }
}

function blobToBase64(blob, callback) {
  var reader = new FileReader();
  reader.onload = function() {
    var dataUrl = reader.result;
    var base64 = dataUrl.split(',')[1];
    callback(base64);
  };
  reader.readAsDataURL(blob);
}

function zipAndSaveFiles(zip) {
  chrome.windows.getLastFocused(function(window) {
    var content = zip.generate(zip);
    var zipName = 'download.zip';
    var dataURL = 'data:application/zip;base64,' + content;
    chrome.downloads.download({
      url:      dataURL,
      filename: zipName,
      saveAs:   true
    });
  });
}

【问题讨论】:

  • 包含更多“上下文”会有所帮助:上面的代码是从哪里执行的 (popup, background-page) ?背景页面和弹出窗口中的相关代码部分是什么? (理想情况下,SSCCE 会很好!)
  • @ExpertSystem 我在上一个问题中问过你这个问题,你告诉我就这个问题提出新的问题检查链接stackoverflow.com/questions/20988041/…
  • 我知道 :) 你很好地提出了这个问题,但为了让 MAC 人员能够更有效地帮助你,你应该提供更多信息(参见我的第一条评论)。跨度>
  • 我有两点意见:1.您正在使用已弃用的chrome.extension.sendRequest/onRequest。请改用chrome.runtime.sendMessage/onMessage。 2.正如我在您之前的问题中已经建议的那样,您应该尝试将压缩和下载委托给后台页面。 (看看我对示例代码的回答。)
  • 让我看看,然后回复你。顺便说一句,我注意到您使用的是 xhr.send("null"); 而不是预期的 xhr.send(null); (尽管对于 GET 请求并没有任何区别。

标签: javascript macos google-chrome google-chrome-extension


【解决方案1】:

这是一个 known bug 在 MAC 上已有 3 年多的时间了。作为一种解决方法,您可以将对话框打开压缩和下载操作委托给您的后台页面。

为了实现这一点,您需要对您的代码进行以下修改(按文件组织):

popup.html(或者随便你怎么称呼它)

删除 JSZip(您现在只需要在后台页面中使用它)。

ma​​nifest.json

// Replace:
"background": {
  "scripts": ["background.js"]
},
// with:
"background": {
  "scripts": ["jszip.js(or whatever the name)", "background.js"]
},

background.js

// Replace:
if (onSuccess) {
    onDownloadComplete(xhr.response, arrayOfUrl, zip);
}
// with:
if (onSuccess) {
    onSuccess(xhr.response, arrayOfUrl, zip);
}

// Replace:
chrome.runtime.getBackgroundPage(function () {
    zipAndSaveFiles(zip);
});
// with:
zipAndSaveFiles(zip);

// Add:
var count;
chrome.runtime.onMessage.addListener(function (msg) {
  if ((msg.action === 'download') && (msg.urls !== undefined)) {
    // You should check that `msg.urls` is a non-empty array...
    count = 0;
    var zip = new JSZip();
    downloadFile(msg.urls[count], onDownloadComplete, msg.urls, zip);
  }
}

popup.js

// Replace:
function downloadLinks() {
    ...
}
// with:
function downloadLinks() {
  var urlArray = new Array();
  for (var i = 0; i < visibleLinks.length; ++i) {
    if (document.getElementById('check' + i).checked) {
      urlArray.push(visibleLinks[i]);
    }
  }
  //var zip = new JSZip();
  //downloadFile(urlArray[count], onDownloadComplete, urlArray, zip);
  chrome.runtime.sendMessage({
    action: 'download',
    urls:   urlArray
  });
}

(正如我已经提到的,我只是在这里猜测,因为我无法重现这个问题。)

【讨论】:

  • 它的工作就像魅力。非常感谢您的精彩而完整的详细回答......
  • 总是乐于助人!如果您真的喜欢我的答案,请随时为我的答案投票:)
  • 现在我在我的 popup.html 中使用 。当点击“选择文件”按钮时,同样的事情也在发生,文件浏览器打开片刻,然后浏览器操作和文件浏览器都会自动关闭。你能检查一下吗?谢谢...
  • 以上问题在MAC OS中
  • 原来这是一个在 OSX 上使用了 3 年多的 known bug。然而,在修复此错误之前(如果可以的话),发布代码可能会帮助某人想出一个解决方法。
猜你喜欢
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多