Mathlight
Mathlight

Reputation: 6653

Add my own onclick function with Greasemonkey

I want to add a button, with an onclick event, to the page. It will eventually open an overlay div.

But, I can't get even an alert running.

I've used a couple of techniques, like unsafeWindow, and adding the script tags to the body, but still doesn't work.

This is the code that I'm using right now:

function main() {
    var script_source = '<script type="text/javascript">function doenwedan(){alert("hebben we gedaan!");}</script>';
    var link_knop = '<br /><br /><br /><br /><button onclick="doenwedan()" value="gaan we doen">gaan we doen</button>';
    var orginele_pagina = document.getElementById('ds_body').innerHTML;
    document.getElementById('ds_body').innerHTML =orginele_pagina + link_knop + script_source ;
}

main();

How can I get this working?
I need a technique like this, because when the overlay div is called, there will be new functions needed, so if got to inject them then...

Upvotes: 3

Views: 6426

Answers (1)

Brock Adams
Brock Adams

Reputation: 93443

Several things:

  1. Don't inject JS if you don't have to (On the Evil Overlord list next to "Don't turn into a snake; it never helps").
  2. Don't futz with innerHTML if you don't have to. It busts things and leads to the temptation of trying to regex HTML.
  3. Use DOM methods to add things, with rare exceptions.
  4. I'm not sure that a script node, created thus, will be parsed anyway.
  5. Might as well start using jQuery. It makes things simpler and more robust.

Putting it all together, your script would become something like:

// ==UserScript==
// @name     _Add a button
// @include  http://YOUR_SERVER/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==

function doenwedan () {
    alert ("hebben we gedaan!");
}

var orginele_pagina = $('#ds_body');
orginele_pagina.append (
    '<br><br><br><br><button id="myButton" value="gaan we doen">gaan we doen</button>'
);

$("#myButton").click (doenwedan);

Upvotes: 2

Related Questions