How to automatically inject JavaScript into web pages so that its variables can be obtained from the developer console

I have a library of JavaScript functions that I want to get from the web browser developer console. I want to be able to perform my functions side by side with the functions and variables defined by the web page.

One of the solutions that I see is to simply copy / paste the code directly into the browser console and then use it, but it would be better if there was a more elegant solution, especially because my code base could grow a lot, and I don’t need to copy / paste every time you boot.

Another solution I reviewed was using Chrome Extensions. The Chrome Extension content scripts ( https://developer.chrome.com/extensions/content_scripts.html#host-page-communication ) allow you to automatically run JavaScript code when visiting web pages, but the above web page indicates that

"[Content scripts cannot] use variables or functions defined by web pages or other content scripts."

Is there any other way to accomplish this?

Thanks for the help!

+4
source share
2 answers

UPDATE (7/7/2013):
I upgraded to Firefox v22 and found out that in this latest version (or in the last few versions ... I'm not sure) the built-in Web Developer tool has a Javascript Scratchpad (press Shift + F4 to pull it) that will allow you to enter the code or , in your case, load the JS file and run it on the loaded page.

I did not test it extensively, but added a couple of variables to the existing page, and they were accessible through the built-in console, as well as into the Firebug console. Just do File > Open File to open the JS file, and then do Execute > Run .


One option is to create a bookmarklet (reusable and can be added to any page), but it works only for the simplest script. See: here

+3
source

As soon as your page is loaded into the browser, all javascript functions will be under the "window" object. For example, if you have,

 function mytestfunciton() { console.log('This is a test'); } 

In the console window, just try these

 window.mytestfunciton(); //and get the response below This is a test 

You can also wrap them in a global variable, something like

 var myapp = {}; myapp.add = function(a,b) { myapp.sumvalue = a + b; console.log('Sum Value:'+myapp.sumvalue); }; myapp.substract = function (a,b) { myapp.differencevalue = a - b; console.log('Difference Value:'+myapp.differencevalue); }; 

All your functions are now wrapped under the global variable myapp, and now you can call them from the console using something like

 myapp.add(5,4); 

or still use the global window object

 window.myapp.add(5,4); 
-2
source

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


All Articles