【问题标题】:How can I use chrome.downloads.onDeterminingFilename to change downloaded file names if the files have extension of jpg or png?如果文件扩展名为 jpg 或 png,如何使用 chrome.downloads.onDeterminingFilename 更改下载的文件名?
【发布时间】:2014-03-29 20:13:09
【问题描述】:

如果文件扩展名为 JPG 或 PNG,我如何使用chrome.downloads.onDeterminingFilename 更改下载的文件名?

我在这里查看示例:

chrome.downloads.onDeterminingFilename.addListener(function(item, __suggest) {
  function suggest(filename, conflictAction) {
    __suggest({filename: filename,
               conflictAction: conflictAction,
               conflict_action: conflictAction});
  }
  var rules = localStorage.rules;
  try {
    rules = JSON.parse(rules);
  } catch (e) {
    localStorage.rules = JSON.stringify([]);
  }
  for (var index = 0; index < rules.length; ++index) {
    var rule = rules[index];
    if (rule.enabled && matches(rule, item)) {
      if (rule.action == 'overwrite') {
        suggest(item.filename, 'overwrite');
      } else if (rule.action == 'prompt') {
        suggest(item.filename, 'prompt');
      } else if (rule.action == 'js') {
        eval(rule.action_js);
      }
      break;
    }
  }
});

这令人困惑。上面的chrome.downloads.onDeterminingFilename 如何检测文件名?一旦它检测到,它是如何更改文件的?任何人都可以分解上面这些代码的含义吗?

参考:http://developer.chrome.com/extensions/samples

【问题讨论】:

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


    【解决方案1】:
    • 一旦确定文件名onDeterminingFilename事件 触发回调函数,它需要 2 参数

      1. item 对象,其中包含下载 id、url、文件名、referrer 等数据(参见 https://developer.chrome.com/extensions/downloads#type-DownloadItem)
      2. __suggest 必须被调用才能同步或异步传递建议。
    • 定义了一个建议函数,用于调用__suggest 根据具体规则
    • 所有规则都从本地内存访问,并运行for循环 遍历它们。
    • 对于基于action 数据在rule 中的每次迭代 使用特定的filename 调用建议函数和 conflictAction

    基本上使用item.filename 获取文件名,并通过调用__suggest 建议新文件名,其中键filename 的值包含新文件名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多