从Chrome扩展background.js向服务器发送URL

Sending URLs to server from Chrome Extension background.js

本文关键字:服务器 URL js Chrome 扩展 background      更新时间:2023-09-26

我正在构建一个简单的Chrome扩展,以在打开每个用户浏览器页面时获取其URL并发送回服务器。我目前可以将URL显示在一个警告框中,但是我的ajax将向数据库返回一个空白值。警报工作正常,尽管(?)

有什么想法吗?请参阅下面的脚本。。

Popup.html:

<html>
    <head>
       <title>Facebook Connect For Chrome Extension</title>
       <script type="text/javascript" src="index.js"></script>
    </head>
    <body>
        <h1>Facebook Connect For Chrome Extension</h1>
        <p><a target="_blank"href="https://www.facebook.com/dialog/oauth?client_id=MY-APP-   ID&response_type=token&scope=email&redirect_uri=http://www.facebook.com">Facebook Connect</a></p>
    </body>
</html>

更新background.js:

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo != undefined) {
var http = new XMLHttpRequest(); 
  http.open("POST",
  "http://ec2-52-89-93-50.us-west-2.compute.amazonaws.com/phpindex.php", 
   true);
  sendme = changeInfo.url
   http.send(sendme);
}
alert(sendme);
}); 

更新manifest.json:

{"name":"Example","版本":"1.0","description":"Example"

"browser_action": {
"default_popup": "popup.html",
"default_icon":"icon.png"
 },
"background": {
"scripts": ["background.js"]
},
"manifest_version":2,
"permissions": [
"tabs",
"http://*.facebook.com/*",
"http://MY_SERVER/*",
"http://*/*",
"https://*/*",
"<all_urls>"
]
}

根据tabs.on激活的文档:

请注意,此事件启动时可能未设置选项卡的URL,但您可以在设置URL时收听onUpdated事件以得到通知。

使用chrome.tabs.onUpdated侦听器回调将url发布到服务器。