2011-10-09 31 views
2

我有一個簡單的書籤應用程序,我正在開發學習Google App Engine。在這一點上,我複製並粘貼到http://ting-1.appspot.com/submit的url,它有一個url字段的表單。由於這很麻煩,我想添加一個Chrome擴展。我只是改變了hello world example,這樣現在我得到的標籤的網址與此代碼(as explained here)如何將Chrome擴展程序中保存的Javascript變量傳遞給Google App Engine應用程序?

<script> 
    window.addEventListener("load", windowLoaded, false); 
    function windowLoaded() { 
     chrome.tabs.getSelected(null, function(tab) { 
     document.getElementById('currentLink').innerHTML = tab.url; 
     tabUrl = tab.url; 
     }); 
    } 
document.write(tabUrl) 
    </script> 

我如何通過tabUrlhttp://ting-1.appspot.com/submit

謝謝!

更新

background.html,我作爲來自Mohamed Mansour's answer改編:

<script> 
    //React when a browser action's icon is clicked. 
    chrome.browserAction.onClicked.addListener(function(tab) { 
     //this gets the url and the title 
     chrome.tabs.getSelected(null, function(tab) { 
      tabUrl = tab.url 
      tabTitle = tab.title 

     //this posts the data to the bookmarking app 
     var formData = new FormData(); 
     formData.append("url", tabUrl); 
     formData.append("title", tabTitle); 
     formData.append("pitch", "this is a note"); 
     formData.append("user_tag_list", "tag1, tag2"); 
     var xhr = new XMLHttpRequest(); 
     xhr.open("POST", "http://ting-1.appspot.com/submithandlertest"); 
     xhr.send(formData); 
     }); 
    }); 
</script> 

回答

4

您正常使用XHR(XMLHttpRequest的)請求。我會把它放在你的background page。按照這裏的例子,https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest。我相信你也想提交數據,所以不要忘記。我想你也想要一個POST請求。從MDC的例子,你可以涉及這樣說:

var formData = new FormData(); 
formData.append("username", "Groucho"); 
formData.append("accountnum", 123456); 
var xhr = new XMLHttpRequest(); 
xhr.open("POST", "http://ting-1.appspot.com/submit"); 
xhr.send(formData); 

確保你有你的manifest的URL,獲取權限,要做到這一點要求。

"permissions": [ 
    "tabs", 
    " http://ting-1.appspot.com/submit" 
], 
+0

@ Mohamed Mansour:謝謝你的回答。這工作完美。另外感謝鏈接到「XMLHttpRequest」教程。現在我想添加一個回調函數來表明提交是成功的。我正在閱讀異步請求部分https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Example:_Asynchronous_request,但如果您有任何關於如何在我的情況下添加回調函數的實用建議,那也是有幫助的,或者如果有必要,我會在以後再發問。我用我使用的代碼更新了問題。再次感謝。 – Zeynel

相關問題