从Chrome扩展插入MySQL

时间:2013-11-18 13:02:02

标签: mysql google-chrome-extension xmlhttprequest

我想点击我的Chrome扩展程序,它会获取当前标签页并将其插入MySQL数据库。看来我必须使用xhr,但是我对它是如何工作的松散掌握。我也略微明白了Chrome Extension → Web App API → MySQL的想法。

到目前为止,我有一个工作的chrome扩展程序,它抓取当前标签页面并显示它和连接到我的数据库的php文件。但是,我可以使用一些帮助获取url变量到Web API然后到我的php文件。

最后,我是一个新手,所以如果对此提出质疑,我会道歉。

修改

这是我的代码和更多细节......

currentUrl.js

//grab the current url

   chrome.tabs.getSelected(null, function(tab) {
       var tabId = tab.id;
       tabUrl = tab.url;

       document.write(tabUrl);
   });

popup.html

<!doctype html>
<html>
  <head>
    <script src="currentUrl.js"></script>
    <script language="javascript" type="text/javascript">

  </head>
</html>

insertdb.php

<?php
$con=mysqli_connect("localhost","root","my_pw","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"INSERT INTO urlHistory (Urls)
VALUES ('Url'");

mysqli_close($con);
?>

的manifest.json

{
  "manifest_version": 2,

  "name": "Current Url",
  "description": "Grab tab's current url",
  "version": "1.0",

  "browser_action": {
    "default_icon": "url_icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs"
    // dont't I have to put something here?
  ]
}

1 个答案:

答案 0 :(得分:3)

您可以使用XHR将URL发送到insertdb.php将要侦听的服务器并将URL存储在数据库中。

有关相关概念的更多信息:


示例代码:
<子> (下面的代码仅用于演示,并未考虑基本概念,例如输入验证,用户授权/验证,错误处理等(所有这些对于生产就绪解决方案都是必不可少的))。

在insertdb.php中:

<?php
if (isSet($_POST['url'])) {
    $con = mysqli_connect('localhost', 'root', 'my_pw', 'my_db');
    ...
    $stmt = mysqli_prepare($con, 'INSERT INTO urlHistory (Urls) VALUES (?)');
    mysqli_stmt_bind_param($stmt, 's', $_POST['url']);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    mysqli_close($con);
}
?>

在background.js中:

function sendCurrentUrl(url) {
  var req = new XMLHttpRequest();
  req.addEventListener('readystatechange', function (evt) {
    if (req.readyState === 4) {
      if (req.status === 200) {
        alert('Saved !');
      } else {
        alert("ERROR: status " + req.status);
      }
    }
  });
  req.open('POST', 'https://your_domain/your/path/insertdb.php', true);
  req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  req.send('url=' + encodeURIComponent(url));
}

chrome.browserAction.onClicked.addListener(function (tab) {
   sendCurrentUrl(tab.url);
});

在manifest.json中:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },

  "permissions": [
    "activeTab", 
    "https://your_domain/*"
  ]
}