user2085388
user2085388

Reputation: 3

How to inject a button that will execute a function?

I'm having real difficulties using Greasemonkey and Firefox javascript to inject a button that, when selected, will execute a function.

For example, I am trying to place the button right after the "Unanswered" button on the SO "Ask a Question" page.

I wish it to run a function that will do anything, say alert ("Hello World") or console.log('TEST start'), for example.

Can someone please post up some sample code to make this work? Once I have a working sample, then I should be able to go from there.

Many thanks in advance.

Upvotes: 0

Views: 4349

Answers (1)

Brock Adams
Brock Adams

Reputation: 93443

The process for this kind of thing is:

  1. Determine the HTML structure of the content you want to modify.
  2. Add or change your new content. Note that jQuery makes it so much easier.
  3. Add, modify, and/or delete javascript event listeners for your new content.
  4. if the target content is added via AJAX methods, use AJAX-compensating techniques.

For your example page:

Inspecting with Firebug shows that the Unanswered "button" HTML looks like this:

<div class="nav mainnavs">
  <ul>
    ...
    <li>
      <a href="/unanswered" id="nav-unanswered">Unanswered</a>
    </li>
  </ul>
</div>


So we will add a "button" like this:

<div class="nav mainnavs">
  <ul>
    ...
    <li>
      <a href="/unanswered" id="nav-unanswered">Unanswered</a>
    </li>
    <li>
      <a href="#" id="gmOurFirstButton">Log something</a>
    </li>
  </ul>
</div>


We'll activate it with jQuery's .click().

For this page and this button, we do not need to worry about AJAX.

Putting it all together, a complete working script looks like:

// ==UserScript==
// @name     _Add a simple button to a page
// @include  https://stackoverflow.com/questions/ask*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
var unansweredBtn   = $("#nav-unanswered");

//-- Add our button.
unansweredBtn.parent ().after (
    '<li><a href="#" id="gmOurFirstButton">Log something</a></li>'
);

//-- Activate the button.
$("#gmOurFirstButton").click ( function () {
    console.log ("Something.");
} );

Upvotes: 2

Related Questions