How to dynamically inject a JavaScript function?

℡╲_俬逩灬. 提交于 2019-12-03 08:59:54

Inject a <script> tag into the <head> which contains a self-invoking function:

var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');

script.src = 'path/to/script.js';    
head.appendChild(script);

Where the referenced script looks something like this:

(function(){
    // do your stuff here    
})();

Edit

How to do it as an inline script:

function fn() {
    alert('hello JS');
}

var head = ...,
    script = ...;

// FF doesn't support innerText
script[script.innerText ? 'innerText' : 'textContent'] = '(' + fn + ')()';
head.appendChild(script);

Demo

You need to define the function in the global scope (put it in the <head> section) to use it where you do.

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");

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!