3

I'm building a script in Greasemonkey that changes the select tag when clicking on a button. However, the current select has already a onChange option that changes the subcategory.

Is there a way to make the script run this?

HTML Code:

<select id="incident.category" name="incident.category" style=";width:160px;width:180px" onchange="onChange('incident.category');"><option value="">-- None --</option><option value="request" selected="SELECTED">Request</option><option value="incident">Incident</option><option value="informational">Informational</option></select>

My code:

document.getElementById("incident.category").value = "informational";
document.getElementById("incident.category").focus();
window.setTimeout(function ()
{
  document.getElementById("incident.subcategory").value = "informational-informational";
  document.getElementById("incident.subcategory").focus();
}, 1000);

the subcategory doesn't appear if the category doesn't fire the onChange which is what is happening right now.

Any ideas?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Xero Kael
  • 132
  • 1
  • 12
  • 1
    In addition to the answers below, there's a lot more info here: http://stackoverflow.com/questions/5006460/userscripts-greasemonkey-calling-a-websites-javascript-functions – Wayne Jan 30 '14 at 20:13

2 Answers2

1

Since this is for Greasemonkey and/or Tampermonkey, you can use unsafeWindow. EG:

document.getElementById("incident.category").value = "informational";
document.getElementById("incident.category").focus();
unsafeWindow.onChange('incident.category');
...


Otherwise, the go-to approach is to inject your script code.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
1

The location hack is a safe and easy way to execute a function defined in the page:

location.assign("javascript:window.onChange('incident.category');void(0)");

It's a lot like running a bookmarklet from within a Greasemonkey script, so it's perfect for scripts that need to a reference only a few things from the page. And, because javascript: URLs always execute in the content scope, this method does not have any of the security concerns that come with using unsafeWindow.

Wayne
  • 59,728
  • 15
  • 131
  • 126
  • One question, if I have another JS function, such as: http://pastebin.aquilenet.fr/?cf54ca256fc42061#/EIn/A1jqxBq87OJWeTGgjGNvgu6Yc4pn55tH+MI17s= how would you call it? I'm still very new at JS and trying to figure out everything :S – Xero Kael Jan 30 '14 at 23:20
  • I think the function to call would be: `AJAXTableCompleter(gel('sys_display.incident.cmdb_ci'), 'incident.cmdb_ci', 'company', 'true');` but it's still giving me headaches – Xero Kael Jan 30 '14 at 23:24
  • in chrome i get this error: Uncaught TypeError: window.onChange is not a function – james turner Mar 03 '16 at 18:44