简体   繁体   中英

Extracting Variable from Javascript Source Using Selenium WebDriver

I am working with a page source that runs Javascript to print text on the page. Here is a snippet of the source I'm speaking of:

var display_session = get_cookie("LastMRH_Session");
if(null != display_session) {
    document.getElementById("sessionDIV").innerHTML = '<BR>The session reference number: &nbsp;' + display_session + '<BR><BR>';
    document.getElementById("sessionDIV").style.visibility = "visible";
}

The page is displaying the value of the display session variable when it's not null but I want to know if there is a way I can utilize this variable in my Selenium WebDriver code. The function that uses this code in the Javascript does not return the display_session variable and I cannot alter the page source. I tried this based on the post here but it throws an exception.

JavascriptExecutor js = (JavascriptExecutor) driverRp; 
Object result = js.executeScript("return display_session");
System.out.println("sessionId = "+result);

Any suggestions?

Figured it out. Needed to go after the cookie itself instead of messing with the Javascript variable.

Cookie cookie = driverRp.manage().getCookieNamed("LastMRH_Session");
String sessionId = cookie.getValue().toUpperCase();
System.out.println("sessionId = "+sessionId);

Found the solution at this post .

If the display_session variable is inside a function the you will not be able to access it unless it is at global scope.

If your intention is to read the value of a cookie, you can use the driver.manage().getCookieNamed(...) as an alternative to executing Javascript.

EDIT:

Just saw that you were able to figure out the same. Didn't see your answer when I posted. Glad it worked out.

尝试这个:

js.executeScript('return get_cookie("LastMRH_Session")')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM