Pregunta

Estoy trabajando en una extensión del navegador usando crossrider.Necesito enviar algunos datos desde la ventana emergente a extension.js

Mi código de ventana emergente

<!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 extensión.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
});

El valor de activeTabUrl no se actualiza.Da valor NULL.PD:Puedo comunicarme entre background.js y popup.Pero por alguna razón la función appAPI.message.toActiveTab no me funciona.¿Dónde estoy cometiendo el error?

Fondo.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 trabajo 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);
        }
    });
    });
  });
¿Fue útil?

Solución

En este ejemplo de código, el URLTabActiva La variable solo se establece una vez que se recibe una respuesta del extensión.js archivo ya que la mensajería es asincrónica por diseño.Por lo tanto, al llamar alert(activeTabUrl); en el código, el mensaje aún no se ha recibido del extensión.js código, por lo tanto, el valor sigue siendo nulo cuando se inicializó.

Usar el URLTabActiva variable debes esperar el mensaje del extensión.js archivo y, por lo tanto, debe colocar el código usando la variable en la devolución de llamada del detector de mensajes, preferiblemente como una función.También tenga en cuenta que el uso de una alerta en el código de la ventana emergente hace que ésta se cierre y, por lo tanto, no debe usarse en el alcance de la ventana emergente.

Probé el siguiente código emergente, que elimina la variable para evitar confusiones y pasa la URL de la pestaña activa como parámetro a la función llamada en el detector de mensajes, y funcionó como se esperaba:

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
}

[Descargo de responsabilidad:Soy un empleado de Crossrider]

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top