Chrome扩展程序:在backgroud.js中回调popup.js

时间:2015-09-11 12:13:08

标签: google-chrome-extension

我有简单的Chrome扩展程序来显示Json的温度。 Background.js:如何将响应temp传递给???在popup.html ????

清单没问题。 清单:

{
    "name": "AlarmText",
    "version": "0.0.1",
    "manifest_version": 2,
    "permissions": ["alarms", "http://api.openweathermap.org/data/2.5/weather?q=London"],

    "icons": { "128": "icons/icon128.png",
               "64": "icons/icon64.png",
               "32": "icons/icon32.png" },  

    "browser_action": {
        "default_title": "Alarm test",
        "default_popup": "popup.html"
    },
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    }
}

在弹出窗口中,我将从URL显示temp。在div id =“out”中,popup.html:

<!doctype html>
<html>
  <head>
    <title>popup</title>
    <script src="popup.js"></script>
    <script src="background.js"></script>
  </head>
  <body>
    <div id="out">???</div>
    <button id="checkPage">Refresh</button>
  </body>
</html>

在popup.js中调用alarm来获取temp。 popup.js:

document.addEventListener('DOMContentLoaded', function() {
    var checkPageButton = document.getElementById('checkPage');
    checkPageButton.addEventListener('click', function() {


        chrome.runtime.sendMessage({greeting: "alert"}, function(response) {

            alert("response");
            document.getElementById('out').innerHTML = response.farewell; 
            document.getElementById('checkPage').innerHTML = response.farewell; 
        });


   }, false);
}, false);

在background.js中有问题:-)如何在popup.html中将数据写入div?为什么不在回调函数中使用sendResponse? background.js

function getTemp(callback) {
  var xhr = new XMLHttpRequest();
  xhr.open ("GET", "http://api.openweathermap.org/data/2.5/weather?q=London", true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // defensive check
      if (typeof callback == "function") {
        // apply() sets the meaning of "this" in the callback
        callback.apply(xhr);
      }
    }
  }
  // send the request *after* the event handler is defined 
  xhr.send();
}

//alarm
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.greeting == "alert"){
            alert("alert alarm");

            getTemp(function() { 
                responseArray = JSON.parse(this.responseText);

                //@TODO how to pass response temp to <div id="out">???</div> in popup.html????
                alert("response get temp: " + responseArray["main"]["temp"]);
                sendResponse({farewell: "goodbye"});
            });
        }
    }
);

谢谢: - )

0 个答案:

没有答案