【问题标题】:Chrome Extension chrome.downloads.download workingChrome 扩展 chrome.downloads.download 工作
【发布时间】:2018-07-02 16:02:30
【问题描述】:

我正在创建一个具有下载文件按钮的扩展程序。 该文件是使用从 chrome 的 localStorage 中检索到的内容创建的。

在 panel.html 我有以下代码:

<!DOCTYPE html>
<html>
<body>
    <button id="btnDownload">Download</button>

    <script src="messaging.js"></script>
    <script src="panel.js"></script>
</body>
</html>

Panel.js 具有以下事件监听器:

 document.querySelector('#btnDownload').addEventListener('click', function() { 
        sendObjectToInspectedPage({action: "download"}); 
    });

sendObjectToInspectedPage 函数在 messaging.js 中:

function sendObjectToInspectedPage(message) {
    message.tabId = chrome.devtools.inspectedWindow.tabId;
    chrome.extension.sendMessage(message);
}

在我的 background.js 文件中,我有以下代码:

chrome.extension.onConnect.addListener(function (port) {

    var extensionListener = function (message, sender, sendResponse) {

        if(message.tabId && message.content) {           
               if(message.action  === 'download') {

                    var aFilePart = ['<a id="a"><b id="b">Hi :) !</b></a>'];
                    var blob = new Blob(aFilePart, {type : 'text/html'});
                    var url = URL.createObjectURL(blob);

                    chrome.downloads.download({
                    url: url 
                    });

                //Pass message to inspectedPage
                } else {
                    chrome.tabs.sendMessage(message.tabId, message, sendResponse);
                }

        // This accepts messages from the inspectedPage and 
        // sends them to the panel
        } else {
            port.postMessage(message);
        }
        sendResponse(message);
    }

    // Listens to messages sent from the panel
    chrome.extension.onMessage.addListener(extensionListener);

    port.onDisconnect.addListener(function(port) {
        chrome.extension.onMessage.removeListener(extensionListener);
    });

});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    return true;
}); 

我想用我传递的内容生成文件,并在单击下载按钮时将文件下载到我的计算机,但这不起作用。

我做错了吗?有什么遗漏吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    你应该使用'runtime'在messaging.js中发送消息

    chrome.runtime.sendMessage(message);
    

    另外,在您的后台脚本中,这不是必需的,

    chrome.extension.onConnect.addListener()
    

    这是一个简单的例子

    function popupMsg(message) {
        if (message.action == "download") {
            //Do Something
        } else {
            //Something else
        } 
    }
    
    chrome.runtime.onMessage.addListener(popupMsg);
    

    这是运行时文档https://developer.chrome.com/apps/runtime

    【讨论】:

      猜你喜欢
      • 2013-02-18
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 2014-12-29
      相关资源
      最近更新 更多