Home > Net >  Selenium C# creating new web element and getting response back
Selenium C# creating new web element and getting response back

Time:07-19

I am creating a new element and trying to get the response back which should be a url but I am not sure how to get the response back from the new element. Any suggestions would be great.

public void Setup()
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        driver = new ChromeDriver("C:\\SeleniumDrivers\\");
        driver.Navigate().GoToUrl("https://www.target.com");
        driver.Manage().Window.Maximize();
        Thread.Sleep(3000);
        string execu = "var document = window.document;" 
        "var head = window.getElementByTagName(\"head\");" 
        "var script = window.createElement(\"script\");"  
        "script.setAttribute(\"type\", \"text/javascript\");"  
        "script.setAttribute(\"src\", \"https://go.playerzero.ai/record/6274691b00fbad01561df689\");" 
        "head.appendChild(script);";
        try
        {
            js.ExecuteScript(execu);

        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e);
        }
    }

CodePudding user response:

Modify your script to return the src:

This is a working example using .NET6, Selenium.WebDriver 4.3.0, Selenium.WebDriver.ChromeDriver 103.0.5060.5300

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

const string Url = @"https://www.target.com";

using var driver = new ChromeDriver();
driver.Navigate().GoToUrl(Url);

var script = @"let script = document.createElement('script');
              script.type = 'text/javascript';
              script.src = 'https://go.playerzero.ai/record/6274691b00fbad01561df689';
              document.head.appendChild(script);
              return script.src;";

var js = (IJavaScriptExecutor)driver; 
var src = js.ExecuteScript(script).ToString();

Console.WriteLine(src);
  • Related