我正在为Chrome扩展程序,我需要将活动标签的网址传递给包含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();
}


感谢帮助。

最佳答案

我认为您应该这样做,因为在代码中,因为XHR.send();时tabs.query是异步的。获取执行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();

  });

}

关于javascript - chrome事件标签网址传递到php文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13406511/

10-12 06:43