简体   繁体   中英

How to access c# variable in javascript in selenium

In the following code, I have a variable linkLocation which I want to access in my JavaScript code. It shows error "Linklocation is not defined". How I will access the variable in the JavaScript code ?

    IWebElement link = driver.FindElement(By.LinkText("soemtext"));
    String linkLocation = link.GetAttribute("href");             
    Console.WriteLine(linkLocation);
    ((IJavaScriptExecutor)driver).ExecuteScript("window.open(linkLocation, 'groupPage')");

On the basis of my experience of how Selenium works in other languages, I'd expect something like this to work:

((IJavaScriptExecutor)driver).ExecuteScript(
    "window.open(arguments[0], 'groupPage')", new Object[] { linkLocation });

(I don't code in C#. Hopefully I don't have an obvious syntax error in the code above.)

The ExecuteScript method takes an optional array of objects that are passed as arguments to the JavaScript code. On the browser side, what you passed to ExecuteScript is executed inside a function so the code above would be equivalent to:

function () {
    window.open(arguments[0], 'groupPage');
}

The kind of concatenation you show in your self-answer is generally unsafe. If double quotes appear in linkLocation (which is possible; in query parameters, for instance), the concatenated string will be invalid JavaScript code.

I changed the last line to :

((IJavaScriptExecutor)driver).ExecuteScript("console.log('" + linkLocation + "'); window.open('" + linkLocation + "', 'groupPage')");

and it worked.

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