EDIT-2: None of the answers seem to work. Not even the one I previously marked as the answer of this question. Any help is appreciated. Thanks.
this seems to do the trick:
function goBackOrGoToUrl() {
window.history.back();
window.location = "http://example.com";
}
Call history.back() and then change the location. If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll go to the location specified.