Search code examples
javascriptgoogle-chromedom-eventsuserscripts

How to dynamically inject a JavaScript function?


I am stuck using a product with a horrible UI at work and trying to make it palatable via UserScripts in Chrome. To that end, I am trying to inject a JavaScript function into the page via the UserScripts mechanism:

// find the div
var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject");

// inject function
dropDown.innerHTML = dropDown.innerHTML + "<script>function gotoIncident(){alert('111')}</script>";        

// inject a button
dropDown.innerHTML = dropDown.innerHTML + "&nbsp;&nbsp;&nbsp;<input type='button' name='btnSearch' value='Go' onClick='javascript:gotoIncident()' >";

As you can see I am injecting a button and a function (gotoIncident) that should fire when the user clicks the button.

The button does appear on the screen but when I click it, the javascript debugger tells me that gotoIncident is not defined.

What am I missing?


Solution

  • For reference I resolved it the following way:

    myDiv.innerHTML = myDiv.innerHTML + " <input type='text' id='txtSearch' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";
    myDiv.innerHTML = myDiv.innerHTML + " <input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";
    
    addScript("function fn() {var obj = document.getElementById('txtSearch'); "
      + "if (obj != null) { "
      + "  var incidentId = document.getElementById('txtSearch').value; "
      + "  var currentURL = location.href; "
      + "  var splitResult = currentURL.split('/'); "
      + "  var projectId = splitResult[4]; "
      + "  location.href = 'http://site/SpiraTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; "
      + " } }"
      , "fn");
    

    }