Search code examples
javascriptgoogle-chromecode-injectionuserscripts

Injecting code into the web page does not work


This is a follow-up to a question I asked yesterday.

I have a userscript (kind of like GreaseMonkey script, but for Chrome).

The idea is to add a textbox and a button to the page. Then when the user clicks the button, it kicks off a function that does stuff. So I inject the textbox, button and the function into the page, but when the user clicks the button, the Chrome console tells me "Uncaught TypeError: object is not a function". So obviously it does not see the function I just injected and that is specified in the onclick event for the button.

So I have code like this:

initialize();

function initialize() { 
    var dropDown = document.getElementById("tstGlobalNavigation_ddlChooseProject"); 

    // add a textbox 
    dropDown.innerHTML = dropDown.innerHTML + "&nbsp;&nbsp;&nbsp;<input type='text' name='txtSearch' style='position:absolute;top:8px;left:800px;width:50px' >";

    // add a button 
    dropDown.innerHTML = dropDown.innerHTML + "&nbsp;&nbsp;&nbsp;<input type='button' name='btnSearch' value='Go' onclick='fn()' style='position:absolute;top:8px;left:860px;width:35px'>";

    addScript("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://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; " 
    + " }" 
    , "fn"); 
}

function addScript(contents, id) { 
    var head, script; 
    head = document.getElementsByTagName('head')[0]; 
    script = document.getElementById(id); 
    if(script != undefined) { 
    head.removeChild(script); 
    } 
    script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.id = id; 
    script.innerHTML = contents; 
    head.appendChild(script); 
}

What am I missing here?


Solution

  • You're not calling the function you created, you're using the id that you give to the script tag... Try changing the code to

    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://dev.myApp.com/ProductTeam/' + projectId + '/Incident/' + incidentId + '.aspx'; " 
        + " } }" 
        , "fn"); 
    

    and you will have a fn() function that can be called