Search code examples
mysqlgoogle-chrome-extensionxmlhttprequest

Insert into MySQL from Chrome Extension


I like to click my chrome extension and it takes the current tabs url and inserts it into a MySQL database. It seems I have to use an xhr, however I a loose grasp of how it works. I also slightly get the idea Chrome Extension → Web App API → MySQL.

So far I have a working chrome extension that grabs the current tabs url and displays it and a php file connecting to my database. However I could use some help getting to url variable to a Web API then to my php file.

Lastly, I am a bit of a newbie so I apologize if this is questioned poorly.

Edit

Here is my code and more details...

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?
  ]
}

Solution

  • You could use XHR to send the URL over to your server where insertdb.php will be listening for and storing URLs in the DB.

    Some more info on relevant concepts:


    Sample code:
    (The code below is for demonstration only and it does not take into account basic concepts, such as input validation, user authorization/authentication, error handling etc (all of which are essential for a production-ready solution).)

    In 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);
    }
    ?>
    

    In 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);
    });
    

    In manifest.json:

    {
      "manifest_version": 2,
      "name": "Test Extension",
      "version": "0.0",
    
      "background": {
        "persistent": false,
        "scripts": ["background.js"]
      },
    
      "permissions": [
        "activeTab", 
        "https://your_domain/*"
      ]
    }