1

我正在为 Chrome 制作扩展程序,我需要将活动选项卡的 url 传递给带有 php 代码的文件。我的 manifest.json 代码:

{  "name": "demo", 
   "version": "1.0",
   "manifest_version": 2,
   "description": "Making your first Google Chrome extension.",
   "browser_action": {
       "default_icon": "icon.png",
       "default_popup": "chrome.html"
   },
   "permissions": [
       "http://www.mysite.com/",
   "tabs"
   ]
}

和 AJAX 代码:

window.onload = function() {
var XHR = new XMLHttpRequest;
chrome.tabs.query({active:true,currentWindow:true},
      function(tab){tabUrl = tab.url;});
XHR.open('GET', 'http://www.mysite.com/chrome/chrome.php?tab='+tabUrl+'', true);
XHR.onreadystatechange = function () {
  if (4 == this.readyState) {
    var status = this.status;
    if (400 > status) {
      var responseText = this.responseText;
      if (responseText) {
        document.getElementById('resultado').innerHTML = responseText;
      }
    }
  }
};
XHR.send();
}

感谢帮助。

4

1 回答 1

0

我认为你应该这样做,因为在你的代码中,因为 tabs.query 是异步的,当 XHR.send(); 执行 tabUrl 尚未设置。

window.onload = function() {
  var XHR = new XMLHttpRequest;
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, function(tab) {

    tabUrl = tab.url;
    XHR.open('GET', 'http://www.mysite.com/chrome/chrome.php?tab=' + tabUrl + '', true);
    XHR.onreadystatechange = function() {
      if(4 == this.readyState) {
        var status = this.status;
        if(400 > status) {
          var responseText = this.responseText;
          if(responseText) {
            document.getElementById('resultado').innerHTML = responseText;
          }
        }
      }
    };
    XHR.send();

  });

}
于 2012-11-22T20:12:33.700 回答