Running the host script from the entered page

I am writing a Safari extension that adds some features to a webpage that I do not own. I would like my JavaScript page with JavaScript to be able to run some JavaScript functions that the host page uses, but it does not work. On the console, I get the message ReferenceError: Can't find variable: function_name .

My script is listed as End Script, so the whole page needs to be loaded. The function is also called from the onclick() handler on the page, for example:

 onclick="function_name($(this).up());" 

I can get a link to this page element, but when I call element.onclick() , I get another error: TypeError: 'undefined' is not a function (evaluating '$(this).up()') .

Oddly enough, when I call the JavaScript function from AppleScript ( do JavaScript "function_name()" in page ), it works fine. How can I call these functions?

+4
source share
2 answers

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> 
+2
source

It does not work because the added script extension is isolated; he cannot see global page objects except the DOM (and vice versa). The way to this security restriction is to have the script you create create a <script> element with the necessary instructions and paste it into the document. For instance:

 var myScriptElement = document.createElement('script'); myScriptElement.innerHTML = 'alert("Page is using jQuery " + $.fn.jquery)'; document.querySelector('head').appendChild(myScriptElement); 

However, the inserted script will not have access to the entered script objects. So, for example, if you try to access the safari extension object from an inserted script, you will get a reference error.

+2
source

Source: https://habr.com/ru/post/1391855/


All Articles