Javascript in Apex page

I have a helper Apex page to be included in custom button as Javascript.
The page is the following:

<apex:page contentType="text/javascript" contorller="HelperController">
function initialize() {
    return {!dataFromController};
}
</apex:page>

I use it in custom button javascript:

{!REQUIRESCRIPT("/apex/MyHelperPage")}
var initResult = initialize(); ....

It works fine, but when I type https://XYZ.salesforce.com/apex/MyHelperPage I see my javascript file as it, not an empty page.
So my question: is there a way to include VisualForce page to custom button’s javascript but avoid showing its content with direct navigation.

Answer

You could pass a parameter in to make it show the javascript and set that in your requirescript.

<apex:page contentType="text/javascript" controller="HelperController">
<apex:outputPanel layout="none" rendered="{!$CurrentPage.Parameters.jsmode = '1'}">
    function initialize() {
        return '{!dataFromController}';
    }
</apex:outputPanel>
</apex:page>

In the example above you’d just add ?jsmode=1 to your URL like so:

{!REQUIRESCRIPT("/apex/MyHelperPage?jsmode=1")}

Attribution
Source : Link , Question Author : Mike Raven , Answer Author : drakored

Leave a Comment