Inject Script into Web Application and get Element Dimensions (coordinates, Layout) - Yash-777/SeleniumDriverAutomation GitHub Wiki

Injecting JS into Web Application, So that the web browser's JavaScript engine will execute it :

  • We are going to inject JavaScript into browsers application, So that it get interpreted by browsers at client side. JavaScript injection techniques are:

1 . As a String.

2 . As a File from Server.

As a String :

If we want to inject JS File as a String. First we need get file content to a String variable and then we can inject the string js to an application by using JavascriptExecutor interface methods. like, executeScript(String script, Object... args), executeAsyncScript(String script, Object... args).

Read file data to a String Variable.

Scanner sc = null;
try {
    sc = new Scanner(new FileInputStream(new File("injectingToDOM.js")));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

String inject = ""; 
while (sc.hasNext()) {
    String[] s = sc.next().split("\r\n");
    
    for (int i = 0; i < s.length; i++) {
        inject += s[i];
        inject += " ";
    }
}

executeScript() : If the script has a return value, then it will return One of these Boolean, Long, String, List or WebElement. Or null.

((JavascriptExecutor) driver).executeScript("return document.title;");

WebElement element = driver.findElement(By.id("foo"));
String name = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].tagName", element);

JavaScript file:

Use Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport. below function is to get Element coordinates of the left-upper corner.

Element coordinates

To get the Layout width and height use these functions on HTMLElement offsetWidth and offsetHeight. Check this link to getAbsoluteBoundingRect Element values.

Dimensions-offset

injectingToDOM.js
-----------------
    var dimensions = {
        json : {'Left' : '0', 'Top' : '0'},

        position : function( element ) {
            dimensions.json.Left = element.getBoundingClientRect().left;
            dimensions.json.Top  = element.getBoundingClientRect().top;

            return dimensions.json;
        }
    };
    return dimensions.position(arguments[0]);

JAVA
----
    Object name = ((JavascriptExecutor) driver).executeScript(inject, "document.querySelector( '.url' )");
    // From browser console « console.log('JSON :', dimensions.position( document.querySelector( '.url' ) ));

NOTE : If you are passing JS-File as String to executeScript(). Then don't use any comments in between JavaScript code, remove all commented data. because we are sending js file data in single line.

As a File from Server

To add external script file to a browser web application. we are creating a 'Script Element' and specifing its source to location of file over server, by this the web application/site loads a script file. In script file if we add any function to the document then we can access through document object. document.ourFunction() - serverJS.js

serverJS.js
-----------
    document.ourFunction =  function( serverJS ){
        var getHeadTag        =    document.getElementsByTagName('head')[0]; 
        var newScriptTag    =    document.createElement('script'); 
        newScriptTag.type    =    'text/javascript'; 
        newScriptTag.src    =    serverJS;
        // adding <script> to the end of <head> tag.
        getHeadTag.appendChild(newScriptTag);
    }
    // document.ourFunction('http://localhost:8088/WebApplication/serverJS.js');

JAVA
----
    jse.executeScript("document.ourFunction('http://localhost:8088/WebApplication/serverJS.js')");

Refused to execute inline event handler because it violates the following Content Security Policy directive:
"script-src 'self' 'unsafe-eval' https://*.flixcart.com ... Either the 'unsafe-inline' keyword, a hash ('sha256-...'),
or a nonce ('nonce-...') is required to enable inline execution.

By Disable Content-Security-Policy 1.0.6: the following code will work fine. Injecting script as String to the bowser for an application.

<button id='doneButton' onclick='document.func()'> Done </button>
<button id='doneButton' onclick='func()'> Done </button>

With out CSP: inorder to work the above function we need to onclick attribute to an element and we need to add the listener funtions to it.


Form java driver if we need to pass a value to the function then use var function with prams otherwise function will execute with but receives the default values.

⚠️ **GitHub.com Fallback** ⚠️