Proper functionality of Chrome Extension chrome.downloads.download

I am currently developing an extension with a feature that allows users to download a file. This file is generated using data retrieved from the localStorage in Chrome.

Within my panel.html file, the code looks like this:

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

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

The event listener in Panel.js is as follows:

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

The function sendObjectToInspectedPage can be found in messaging.js:

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

The following code snippet is from my background.js file:

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);
                }

        } else {
            port.postMessage(message);
        }
        sendResponse(message);

    }

    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;
}); 

Although I have set up the functionality to generate and download the file upon clicking the button, it doesn't seem to be working correctly. Can you please provide any insights on what might be going wrong or if there's something missing?

Thanks!

Answer №1

For sending messages in messaging.js, it's recommended to utilize the 'runtime' method.

chrome.runtime.sendMessage(message);

In your background script, the following code is not necessary:

chrome.extension.onConnect.addListener()

Below is a straightforward example:

function popupMsg(message) {
    if (message.action == "download") {
        //Do Something
    } else {
        //Something else
    } 
}

chrome.runtime.onMessage.addListener(popupMsg);

Refer to the runtime documentation for more information here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to extract data from a chosen radio button choice

Excuse me, I have a form with an input field and radio buttons. Can someone please help me with how to retrieve the value of the selected radio button and then populate that value into the input text field? For reference, here is the link to the jsfiddle: ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

Unattractive destructuring during conditional assignment

When working with object properties, ESLint often suggests using object destructuring. However, this can sometimes result in redundant lines of code. ESLint may not allow something like the following (which might seem like the preferable approach): const ...

The computation outcome is not being displayed within the <h2> tag. Issue may be related to either

I am currently working on a percentage calculator. The calculation is functioning properly but the result is only being displayed in the input. I would like the result to also be shown in the h2. Is there a way to achieve this? $(document).on("change ke ...

Angular 5 browser console displaying a communication from the server

I recently encountered an issue in Angular5 while trying to log into my account. Whenever there is a wrong password error, it displays a message in the browser console indicating server error 500. However, I do not want this message to be shown in the brow ...

Retrieving JQuery Results Based on List Items

Once I have obtained the list id from the navigation, my next step is to send the id to a PHP file that will return a JSON list. Below is the jQuery syntax I am using: $("#ul_navigation li").click(function(e) { idsec = this.id; alert(idse ...

Utilizing AngularJS ng-repeat, generate dynamic HTML content by calling a function to retrieve data

Just starting out with angularjs and trying to unravel the mystery here. Using ng-repeat: <li class="widget flip-container" ng-repeat="widget in widgets"> <div class="widgetContent" ng-bind-html="getData(widget.UserWidgetId,widg ...

The functionality to disable the submit button for unchecked radio buttons is not functioning properly

I am currently working on a form where I need to disable the submit button until all fields are filled out. Everything is functioning properly for other field types, EXCEPT FOR RADIO BUTTONS. Even when we do not select a radio option, the Submit button s ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...

Retrieve all users along with their respective posts, ensuring that each post is also accompanied by its corresponding comments in

In my Laravel project, I have set up Eloquent models for User, Post, and Comment. The relationships are as follows: User model public function posts(){ return $this->hasMany('App\Post'); } public function comments(){ return $t ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

I am unable to comprehend the function definition

I have familiarity with different types of JavaScript function declarations such as expression functions and anonymous functions. However, I am unsure about the syntax used in these two specific functions: "manipulateData: function (input)" and "getDataByI ...

Stop images from flipping while CSS animation is in progress

I've been developing a rock paper scissors game where two images shake to mimic the hand motions of the game when a button is clicked. However, I'm facing an issue where one of the images flips horizontally during the animation and then flips bac ...

Guide on setting up and customizing run.json within the latest JetBrains Fleet for Next.js

I've been attempting to set up input/output for the latest IDE from JetBrains, Fleet. However, I've hit a roadblock and can't seem to figure it out on my own. That's why I'm turning to the Stack Overflow community for help - how do ...

ReactAppI am facing an issue where the browser fails to refresh the page upon saving changes in my JavaScript file using the VS code editor

Can anyone remind me of the tool we can install to refresh the browser page automatically whenever we save changes in our editor? ...

Creating a messaging platform

I'm trying to figure out the best approach for developing a chat application that can handle thousands of users. I'm unsure about how to efficiently ping the server using AJAX at intervals of every second or less, and then check for any new reco ...

Having trouble with Window.open on Mobile Devices and Canvas?

I've created a unique "button" within the div element. This button is designed to detect user interaction, such as clicks or taps, and when triggered, it should open a new window with the URL: "http://www.google.com". However, while this functionality ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

Retrieving Array keys from PHP using jQuery

As a beginner in jQuery, I am eager to learn how to retrieve Array keys from a php file using jQuery. Currently, I have jQuery code set up to send input to file.php and execute a query on every keyup event. When file.php echoes the result, it looks somet ...