O envio de dados do pop-up para extension.js não funciona
-
21-12-2019 - |
Pergunta
Estou trabalhando em uma extensão de navegador usando crossrider.Preciso enviar alguns dados do popup para extension.js
Meu código de pop-up
<!DOCTYPE html>
<html>
<head>
<!-- This meta tag is relevant only for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
/************************************************************************************
This is your Popup Code. The crossriderMain() code block will be run
every time the popup is opened.
For more information, see:
http://docs.crossrider.com/#!/api/appAPI.browserAction-method-setPopup
*************************************************************************************/
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'});
alert(activeTabUrl);
// THE REST OF YOUR CODE
}
</script>
</head>
<body>
Hello World
</body>
</html>
Código de extensão.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
});
O valor de activeTabUrl não está sendo atualizado.Fornece valor NULL.P.S:Consigo me comunicar entre background.js e pop-up.Mas, por algum motivo, a função appAPI.message.toActiveTab não está funcionando para mim.Onde estou cometendo o erro?
Background.js (editar)
var tabUrl='';
/* appAPI.tabs.getActive(function(tabInfo) {
tabUrl = tabInfo.tabUrl;
}); */
appAPI.message.addListener(function(msg) {
appAPI.tabs.getActive(function(tabInfo) {
tabUrl = tabInfo.tabUrl;
});
var dataString = '{"url":"'+tabUrl+'","access":"'+msg.access+'","toread":"'+msg.toread+'","comment":"'+msg.comment+'"}';
alert(dataString);
appAPI.request.post({
url: 'REST API URL',
postData: dataString,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
appAPI.message.toPopup({
response:response
});
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
Código de trabalho de Background.js
appAPI.message.addListener(function(msg) {
appAPI.tabs.getActive(function(tabInfo) {
var dataString = '{"url":"'+tabInfo.tabUrl+'","access":"'+msg.access+'","toread":"'+msg.toread+'","comment":"'+msg.comment+'"}';
// alert(dataString);
appAPI.request.post({
url: 'http://fostergem.com/api/bookmark',
postData: dataString,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
appAPI.message.toPopup({
response:response
});
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
});
Solução
Neste exemplo de código, o ativoTabUrl variável só é definida quando uma resposta é recebida do extensão.js arquivo, pois a mensagem é assíncrona por design.Portanto, ao ligar alert(activeTabUrl);
no código, a mensagem ainda não foi recebida do extensão.js código, portanto, o valor ainda é nulo quando foi inicializado.
Para usar o ativoTabUrl variável você deve esperar pela mensagem do extensão.js arquivo e, portanto, você deve colocar o código usando a variável no retorno de chamada do ouvinte de mensagem, de preferência como uma função.Observe também que usar um alerta no código pop-up faz com que o pop-up feche e, portanto, não deve ser usado no escopo do pop-up.
Testei o seguinte código popup, que elimina a variável para evitar confusão e passa a URL da aba ativa como parâmetro para a função chamada no listener de mensagens, e funcionou conforme o esperado:
function crossriderMain($) {
// Message listener for response from active tab
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url') ShowPageUrl(msg.url);
});
function ShowPageUrl(url) {
$('#page-url').html('<b>Page URL</b>: ' + url);
}
// Request URL from active tab
appAPI.message.toActiveTab({type: 'active-tab-url'});
//alert(activeTabUrl);
// THE REST OF YOUR CODE
}
[Isenção de responsabilidade:Eu sou um funcionário da Crossrider]