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!