2

In Selenium using Webdriver and C# how we can change the browser title? Using javascript and jQuery as follow:

document.title='XXX'

or

$('title')[0].text='XXX'

Have no effect although we can change the title using Web developers tool console.

Is there any restriction in changing browser title in Selenium?

UPDATE:

Problem roots: Using JavaScriptExecutor that has been initialized with the driver on a window which had been closed.

Milad
  • 539
  • 8
  • 21

1 Answers1

4

As said in this answer, you can run javascript code from selenium.

Your code will be like this:

WebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("document.title = 'hello'");

And it will change browser title.

Edit

Here full working code:

        ChromeOptions options = new ChromeOptions();
        options.AddArguments("--start-maximized");
        var driver = new ChromeDriver(options);

        driver.Navigate().GoToUrl("http://www.google.com");
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        string title = (string)js.ExecuteScript("document.title = 'hello'");

And here result: enter image description here

Community
  • 1
  • 1
Ygalbel
  • 5,214
  • 1
  • 24
  • 32
  • It seems my problem was in JavaScriptExecutor that I used. I had been initialized it somewhere else. – Milad Feb 22 '17 at 11:59
  • Bit of a necropost, but you can also treat driver as an IJavaScriptExecutor directly, ie ((IJavaScriptExecutor)driver).ExecuteScript() – Statharas.903 Jun 07 '22 at 15:00