[SalesForce] how to get current salesforce instance in script of a VF page

I have below code

    <apex:page>
<script type="text/javascript">
    function Test(){
        var url = 'https://ap1.salesforce.com/00O900000070URt';
        window.parent.location.replace(url);
    }
</script>
<apex:outputLink onclick="Test();">
    <analytics:reportChart reportId="00O900000070URt"></analytics:reportChart>
</apex:outputLink>
</apex:page>

If you can observe the var url is hard coded with current instance which will fail if we move this code to prod or any other environment.

please advice how to handle this

Best Answer

Try this. you need to get the first part below in apex controller and use a controller variable in javascript to access the value.

Documentation for URL class here

URL.getSalesforceBaseUrl().toExternalForm()/addtheidthat you want to

In Apex class you will get the URL and Id you want to append,

    public String reportsURL{get; set; } 
    reportsURL = 'URL.getSalesforceBaseUrl().toExternalForm()'+Idoftherecord; 
//set this in the constructor of apex class 

In javascript just access and get the variable

<script type="text/javascript">
    function Test(){
        var url = '{!JSENCODE(reportsURL)}';//variable you created in apex controller
        window.parent.location.replace(url);
    }
</script>