Chrome插件开发Cannot read property 'download' of undefined - 小众知识

Chrome插件开发Cannot read property 'download' of undefined

2020-08-12 01:39:37 苏内容
  标签: Chrome
阅读:5485

I am trying to download a file (image) from a URL via a Chrome Extension using chrome.downloads, but for some reason chrome.downloads is undefined (getting the warning: Cannot read property 'download' of undefined). I am basing my attempt on example from Google.

My test-extension does not have any popup, just a basic manifest and an extremely simply JavaScript file.

manifest.json:

{
    "manifest_version": 2,
    "name": "Testing chrome.downloads.download",
    "version": "0.0.1",
    "permissions": [
        "activeTab",
        "downloads",
        "<all_urls>"
    ],
    "content_scripts": [{
        "matches": [
            "http://www.example.com/*"
        ],
        "js": [
            "jquery.js",
            "index.js"
        ]
    }]}

index.js:

$(document).ready(function () {
  link = 'http://example.com/image.jpg';
  chrome.downloads.download({
    url: link,
    filename: './' + link.substr(link.lastIndexOf('/')+1),
    saveAs: false
  });});

So, how can I make this work?


因为下载命令只能在 background.js里面触发

So after some research i see content scripts dont directly support downloads, but you can pass message to your background page which supports download. The reason i included background page was to be able to see the console ;) you can try to directly goto background.js

manifest.json

{
  "name": "Download static images",
  "description": "Downloads images defined with <img> tag from watched webpage(s) by injecting a script",
  "version": "1.0",
  "browser_action": {
    "default_icon": "debuggerPause.png",
    "default_title": "get page html"
  },
  "background": {
    "page": "background.html"
  },
  "content_scripts": [
    {
      "matches": ["http://stackoverflow.com/*"],
      "js": ["main.js"]
    }
  ],
  "permissions": [
      "tabs", 
      "background","downloads"
  ],
  "manifest_version": 2}

main.js

function getHtml() {
  var pagehtml = document.documentElement;
  var imgs=pagehtml.getElementsByTagName( 'img' );
  var pass_array=[];
  for (i in imgs){
    pass_array.push(imgs[i]["currentSrc"]);
  }
  console.log(pass_array);
  var param = {collection : pass_array};
  chrome.runtime.sendMessage(param);};getHtml();

background.js

chrome.runtime.onMessage.addListener(
  function(arg, sender, sendResponse) {
    var args=arg.collection;
    for (i in args){
    var img_url=args[i];
    try{
     saveas=img_url.replace(/[^a-zA-Z0-9]/g,'-');
    }
    catch (problem){
    }

     chrome.downloads.download({
     url: img_url,
     filename: saveas,
    saveAs: false
    });
   }});

  function sendResponse(){
  }

backgroundpage.html

<script src="background.js"></script>


扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1