Since you are using history.back()
there is no need to check if a product has a category. When coming from the search results the product has no category attached to it.
So you can remove the if
statement. This way the button will behave just like pressing back
in the browser. It will take you to the previous page no mater what. Even if you clicked on a related product or if you come from the cart page.
EDIT
Here is a way to get the page referrer
Mage::app()->getRequest()->getServer('HTTP_REFERER');
You can check if the referred contains the string /catalogsearch/
and add it to your if
statement.