I'm currently trying to write an extension for Google Chrome, which can be used to upload files.
There are two pages: the background page and the popup page.
The popup page appears when you click the icon right of the omni-bar. You can specify the file you want to upload using the standard HTML <input type='file' ... />
.
After selecting the file, and clicking "Upload", the name(+path) of the file should be sent to the background page. This, because the popup can be closed by the user by simply clicking somewhere else on the screen, which closes the page.
When the popup is active, and the background page is uploading the file to the server, the popup should also recieve the progress of uploading(0-100%) from the background page, and display this information. When finished, the user should see the URL.
The problem is, I don't know how to communicate between these two pages. The documentation isn't very clear about how this works. A thing I've tried, is making a function on the background page, called upload(filename)
, and put this code in the popup page:
var BGPage = chrome.extension.getBackgroundPage();
BGPage.upload(the_filename);
But it didn't work, the function wasn't called.
Does anyone know how I can send the filename from the popup page to the background page, and how to retrieve upload status(and eventually the link) from the background page, via the popup page?
Thanks in advance!
forEach((tab) => { chrome. tabs. sendMessage( tab.id, youtPayload, function (response) { // do something here if you want } ); }); }); That's it!
In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions.
Chrome has documentation on sending messages from webpages to chrome extensions. You add an “externally_connectable” object to your manifest. This will specify which webpages you want to allow to communicate with your extension (in this case, localhost, since I was developing on my machine).
Define it as a variable.
background.js
upload = function(fileName) {
console.log('Uploading', fileName);
}
popup.html
<script src="popup.js"></script>
popup.js
var BGPage = chrome.extension.getBackgroundPage();
BGPage.upload(the_filename);
That should work. If it doesn't, then check your inspector for the popup and background page:
It will open the inspector, then click on console to see the error messages in the console to assist you further, doing what I stated above should work, I do it all the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With