The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Archive for February 26th, 2012

Salesforce: JavaScript Remoting and Managed Packages

with 16 comments

I love the crap out of JavaScript Remoting, but came across a small bug when wrapping up the code in a managed package. As many of you know when you create a managed package it prepends your code with a unique name to prevent code conflicting e.g. a page controller called “MyController” becomes “MyPackage.MyController” where “MyPackage” is the prefix you’ve chosen for your managed package.

The bug I’ve found is caused by the fact that the prefix isn’t applied to the JavaScript that calls your Apex Remoting methods i.e you might have an Apex method called “myMethod” which is called like so outside of a managed package environment:

MyController.myMethod(parameters, function(result, event) {
}, {escape: false});

Once you package up your code however this call will no longer work, and if you look in the debugging console of your browser you’ll find an error something like: “MyController is not defined”

This is because in the managed package environment “MyController” actually doesn’t exist but is now called “MyPackage.MyController”! @greenstork and others have come up with a solution for this and it looks something like:

[Edit] One of the Salesforce guys has given me a very neat workaround:

// Check if "MyPackage" exists
if(typeof MyPackage === 'undefined'){
  // It doesn't, so create an object with that name
  window["MyPackage"] = {};

  MyPackage.MyController = MyController;

// All code only refers to MyPackage.Controller
MyPackage.MyController.myMethod(parameters, function(result, event) {
}, {escape: false});

I’ve posted a message on the forums about this issue and Salesforce is aware and is working on it. Now that’s great customer service!

As an aside I’d love to know how they’re going to solve this issue! It’s quite complex because their compiler needs to run through all of your JavaScript code (including any libraries you might have included) and try to figure out what code is actually making remoting calls, and prefix that exclusively! This is a new problem for managed packaging because for the first time they need to work on code that isn’t necessarily 100% part of their platform. This is further complicated because you can Zip your resources. An interesting challenge indeed...

Written by Wes

February 26, 2012 at 7:32 pm

Posted in SalesForce

%d bloggers like this: