问题
I am developing a browser extension using crossrider. I have some resource pages like popup.html and popup.js. In popup.html, there is a form and when user submit the form I want to send the data to my server, which is straight forward. But I also want to send the active tab url along with the form data. But we can get the active tab url in background.js only. To do this I need to send the form data to background.js and then post them to my server.
So my question is how to send data from popup.js (popup window) to background.js ?
回答1:
In answer to your direct question, you can send data from the popup scope to the background scope using appAPI.message.toBackground.
However, I think it would be more efficient to get the active tab's URL when the popup is opened so that it's available in the popup when the form is submitted. You can achieve this by requesting the active tab's URL directly from the active tab and saving the response in a var in the popup scope, as follows:
popup.html:
function crossriderMain($) {
// var to store active tab's URL
var activeTabUrl = null;
// Message listener for response from active tab
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url') activeTabUrl = msg.url;
});
// Request URL from active tab
appAPI.message.toActiveTab({type: 'active-tab-url'});
// THE REST OF YOUR CODE
}
extension.js:
appAPI.ready(function($) {
// Message listener
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url')
// Send active tab's URL to popup
appAPI.message.toPopup({
type: 'active-tab-url',
url:encodeURIComponent(location.href)
});
});
// THE REST OF YOUR CODE
});
[Disclaimer: I am a Crossrider employee]
来源:https://stackoverflow.com/questions/21017681/how-to-send-data-from-popup-script-to-background-js-in-crossrider