简体   繁体   中英

Communication between background page and popup page in a Chrome Extension

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!

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:

  • Popup Inspector: Right click on the popup and choose Inspect
  • Background Inspector In your extension settings page chrome://extensions, turn on developer mode (check top right), and click on background.js .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM