Triggering script functions with inserted buttons

18 views
Skip to first unread message

Peter Blake

unread,
Feb 7, 2020, 6:25:45 PM2/7/20
to greasemonkey-users
I'm looking for help with a script I'm writing to hide unwanted search results on Scribd using GM 4.9 and Firefox 72.

This old script from 2012 seemed to do a similar job on Craigslist, so I set about updating it re-tooling it for my needs. However, the buttons I add to the page can't see the functions in the script that need to trigger in response to a click (log shows "ReferenceError: hideListing is not defined").

I did some poking around and thought that something along the lines of:
Components.utils.exportFunction(hideListing, unsafeWindow, { defineAs: "hideListing" });
might solve my problem, but to no avail.

My programming skills are very rusty, so I'd appreciate any help or insight you can offer.

Thanks,
Peter

LWChris

unread,
Feb 7, 2020, 7:39:03 PM2/7/20
to greasemon...@googlegroups.com

Attach the functions via addEventListener to the button element when you create it. If you define the function above the function you create the button in, it should work fine. It looks something like this:

// ==UserScript==
// @name     Button click demo
// @version  1
// @author   LWChris
// @include  https://www.w3schools.com/jsref/met_element_addeventlistener.asp
// @grant    none
// ==/UserScript==


function theButtonWasClicked() {
  alert("Hello World!");
}

function addTheButton() {
  var btn = document.createElement("button");
  var content = document.createTextNode("Say hello");
  btn.appendChild(content);
  btn.addEventListener("click", theButtonWasClicked);
  document.getElementById("main").appendChild(btn);
}

addTheButton();

Chris

--
You received this message because you are subscribed to the Google Groups "greasemonkey-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to greasemonkey-us...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/greasemonkey-users/b89d537d-827e-43f1-ae4d-01fc52c8c29c%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages