I can extend the answer from canisbos. You can contact the inserted script using the PostMessage function.
the script is introduced:
//insert script to page var myScriptElement = document.createElement('script'); myScriptElement.innerHTML = 'window.addEventListener("message", function(e) {' + ' if (e.data.msg == "do") {' + ' foo(e.data.info);' + ' postMessage({msg: "done", info: "answer"}, "*");' + ' };' + '}, false);' document.querySelector('head').appendChild(myScriptElement); //add answers listener window.addEventListener('message', function(e) { if (e.data.msg == 'done') { console.log(e.data.info); }; }, false); //add the testing function on the body click document.addEventListener('click', function (e) { //call inserted script postMessage({msg: 'do', info: 'from inject'}, '*'); }, false);
Check html page:
<html> <script> function foo(text) { console.log(text); }; </script> <body> <button id='button' onclick='foo("from page")'>test</button> </body> </html>
source share