문제

저는 crossrider를 사용하여 브라우저 확장 프로그램을 개발 중입니다.팝업에서 Extension.js로 일부 데이터를 보내야 합니다.

내 팝업 코드

<!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>

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
});

activeTabUrl 값이 업데이트되지 않습니다.NULL 값을 제공합니다.추신 :background.js와 팝업 간에 통신할 수 있습니다.하지만 어떤 이유로 appAPI.message.toActiveTab 기능이 작동하지 않습니다.내가 어디서 실수를 하고 있는 걸까?

Background.js(편집)

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);
        }
    });
  });

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);
        }
    });
    });
  });
도움이 되었습니까?

해결책

이 코드 샘플에서는 activeTabUrl 변수는 응답이 수신된 후에만 설정됩니다. 확장자.js 메시징은 설계상 비동기식이므로 파일입니다.그러므로 전화할 때 alert(activeTabUrl); 코드에서 메시지는 아직 수신되지 않았습니다. 확장자.js 코드이므로 초기화된 값은 여전히 ​​null입니다.

사용하려면 activeTabUrl 변수에서 메시지를 기다려야 합니다. 확장자.js 파일이므로 메시지 리스너의 콜백에 있는 변수를 사용하여 코드를 배치해야 하며, 가급적이면 함수로 배치해야 합니다.또한 팝업 코드에서 경고를 사용하면 팝업이 닫히므로 팝업 범위에서 사용해서는 안 됩니다.

혼란을 피하기 위해 변수를 사용하지 않고 활성 탭 URL을 메시지 리스너에서 호출된 함수에 매개변수로 전달하는 다음 팝업 코드를 테스트했는데 예상대로 작동했습니다.

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
}

[부인 성명:저는 크로스라이더 직원입니다]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top