2

I need to detect when the url in the browser changes whether it was because of click on a link, a form post or I changed the url in code.

I need it because I'm creating an object to represent the page and I need to dispose recreate it when the url changes.

Here is what I have tried so far:

private string _pageUrl;
protected T _page = default(T);
protected T Page
{
    get
    {
        if (_page == null || UrlHasChanged())
        {
            _page = GetPage<T>();
            SetPageUrl();
        }
        return _page;
    }
}

private bool UrlHasChanged()
{
    var driver = Session.GetDriver();
    return driver.Url != _pageUrl;
}

public void SetPageUrl()
{
    _pageUrl = Session.GetDriver().Url;
}

This works in most cases but it fails when the test goes forward a page and then goes back to the initial page.

I need a way to detect when the url changes so I can reset the _page field.

1 Answer 1

6

I'm a Java developer, so, I search in the C# documentation what looked similar to the Java API. I think you should use the EventFiringWebDriver :

EventFiringWebDriver firingDriver = new EventFiringWebDriver(driver);
firingDriver.NavigatingBack += new EventHandler<WebDriverNavigationEventArgs>(...);
firingDriver.NavigatedBack += new EventHandler<WebDriverNavigationEventArgs>(...);
firingDriver.NavigatingForward += new EventHandler<WebDriverNavigationEventArgs>(...);
firingDriver.NavigatedForward += new EventHandler<WebDriverNavigationEventArgs>(...);

I looked at the unit tests and I found this one that may be useful for you : http://selenium.googlecode.com/svn/trunk/dotnet/test/WebDriver.Support.Tests/Events/EventFiringWebDriverTest.cs

Sign up to request clarification or add additional context in comments.

4 Comments

I think this won't work when the URL has changed after eg. clicking a link/button.
EventFiringWebDriver sadly only functions whey you explicitly call the Navigate() method
@HappyBird have you found a solution for that?
@garryman you are free to implement more listener methods which may lead to URL change, such as NavigateTo, ClickOn, ChangeValueOf, etc. This will handle mouse clicks as well as key strokes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.