Question

I need some advice for the best approach to use in developing embeddable widgets that my site users could use to show our content on their site.

Let's say we have some content which uses a jQuery plugin to be rendered, and we want to give our customers an easy way to embed it in their websites.

One option could be of using an IFrame, but as we know this is quite invasive and has some problems. I'd like to know your opinion on that, too.

Another approach could be giving a code like this, to show item #23:

<DIV id="mysitewidget23"><script src="http://example.com/scripts/wdg.js?id=23" /></DIV>

And somehow (help needed here...) creating the wdg.js server-side script to inject content, jQuery, needed plugins, inside the DIV.

This looks more promising, since the user can customize to a certain extent the style of the DIV, and no IFRAME is needed. But which is the best and more efficient way to do this in ASP.NET MVC?

There are of course many other approaches to achieve what we need.

Was it helpful?

Solution

JSONP is one way to do this. You start by writing a custom ActionResult that will return JSONP instead of JSON which will allow you to work around the cross-domain Ajax limitation:

public class JsonpResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;

        if (!string.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }

        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }

        if (Data != null)
        {
            var request = context.HttpContext.Request;
            var serializer = new JavaScriptSerializer();
            if (null != request.Params["jsoncallback"])
            {
                response.Write(string.Format("{0}({1})",
                    request.Params["jsoncallback"],
                    serializer.Serialize(Data)));
            }
            else
            {
                response.Write(serializer.Serialize(Data));
            }
        }
    }
}

Then you could write a controller action that returns JSONP:

public ActionResult SomeAction()
{
    return new JsonpResult
    {
        Data = new { Widget = "some partial html for the widget" }
    };
}

And finally people can call this action on their sites using jQuery:

$.getJSON('http://www.yoursite.com/controller/someaction?jsoncallback=?',
    function(json)
    {
        $('#someContainer').html(json.Widget);
    }
);

If users don't want to include jQuery on their site you might write JavaScript code on your site that will include jQuery and perform the previous getJSON call, so that people will only need to include a single JavaScript file from the site as in your example.


UPDATE:

As asked in the comments section here's an example illustrating how to load jQuery dynamically from your script. Just put the following into your JavaScript file:

var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (!jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {
        $(function() {
            $.getJSON('http://www.yoursite.com/controller/someaction?jsoncallback=?',
                function(json) {
                    // Of course someContainer might not exist
                    // so you should create it before trying to set
                    // its content
                    $('#someContainer').html(json.Widget);
                }
            );
        });
    }
}
initJQuery();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top