Exit Full View

Traffic People Greasemonkey

I wrote this script for Nalin, he maintains the Traffic People Shop, and I thought it would be nice to jump from the shop to the back-end.

// ==UserScript==
// @name           Traffic People - Products
// @namespace      nickthecoder.co.uk
// @include        http://www.trafficpeople.co.uk/shop/products/*
// ==/UserScript==

var productDetails = document.getElementById( "ProductDetails" ); // Finds the div that holds info about the product
var h2s = productDetails.getElementsByTagName( "h2" ); // Get all of the "h2s" - there should only be 1

if ( h2s.length > 0 ) {

  var h2 = h2s[ 0 ]; // We are only interested in the zeroth "<h2>" tag.

  var productId = getFormElement( "product_id" ).value;

  // Build the html we want to display
  var html = '<div style="position: absolute; right: 0px;">';
  html += '<a href="http://www.trafficpeople.co.uk/shop/admin/index.php?ToDo=editProduct&productId=' + productId + '">Edit</a>';
  html += ' &nbsp; ';
  html += '<a href="http://nickthecoder.co.uk/pinkwino/view/Traffic+People+Greasemonkey" title="Greasemonkey Extension"><img src="http://nickthecoder.co.uk/pinkwino/media/greasemonkey.png" alt="greasemonkey"/></a>';
  html += '</div>';

  // Create a div to put this html into. Note we have 2 divs, an "position: absolute" inside a "position: relative", a common css trick ;-)
  var div = document.createElement("div");
  div.innerHTML = html;

  h2.parentNode.insertBefore( div, h2 ); // This is where the html document is actually altered (by inserting the new div)
  div.style.position = "relative"; // Not sure, but I don't think I can set style.position until it has been added to the document.
 
}
// Its annoying when web sites don't use ids for form or data inside the forms.
// Because we have to resort to using the form elements names instead.
function getFormElement( name ) {
  var forms = document.getElementsByTagName( "form" );
  var i, j;
  for (i = 0; i < forms.length; i ++ ) {
    for (j = 0; j < forms[i].elements.length; j ++ ) {
      if (forms[i].elements[j].name == name) {
        return forms[i].elements[j];
      }
    }
  }
  return null;
}