Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)
I'm using selenium python web driver in order to browse some pages. I want to inject a JavaScript code in to a pages before any other JavaScript codes get loaded and executed. On the other hand, I need my JavaScript code to be executed as the first JavaScript code of that page. Is there a way to do that by Selenium?

I googled it for a couple of hours, but I couldn't find any proper answer!

1 Answer

0 votes
by (62.9k points)

If you cannot modify the page content, you may use a proxy, or use a content script in an extension installed in your browser. Doing it within selenium you would write some code that injects the script as one of the children of an existing element, but you won't be able to have it run before the page is loaded (when your driver's get() call returns.)

String name = (String) ((JavascriptExecutor) driver).executeScript(

    "(function () { ... })();" ... 

If you can instrument your page with a minimal harness, you may detect the presence of a special url query parameter and load additional content, but you need to do that using an inline script. The pseudocode is shown below:

<html>

    <head>

       <script type="text/javascript">

       (function () {

       if (location && location.href && location.href.indexOf("SELENIUM_TEST") >= 0) {

          var injectScript = document.createElement("script");

          injectScript.setAttribute("type", "text/javascript");

 

          //another option is to perform a synchronous XHR and inject via innerText.

          injectScript.setAttribute("src", URL_OF_EXTRA_SCRIPT);

          document.documentElement.appendChild(injectScript);

 

          //optional. cleaner to remove. it has already been loaded at this point.

          document.documentElement.removeChild(injectScript);

       }

       })();

       </script>

    ...

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium online training

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...