AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Monday, 22 February 2016

Create browser extension using WCF & Kangoextensions

Kango framework is a cross-browser extensions framework named Kango. Purpose of Kango is to make browser extensions. With Kango we can create extension for all major browser in minutes using JavaScript only.  In this tutorial I will discuss how to use kango with ASP.NET WCF service with an example.

Requirements

Create new project
Create new project using below command.
python kango_dir/kango.py create "path/to/TestExtension"

File directory structure will appears as shown below image.


Go to src>common folder  & open extension_info.js file & give refrence of background_scriptscontent_scripts files.-

1-background_scripts File : It always run in browser background.
2- content_scripts: It always called on new page.

Let's start plugin implementation.

Step 1 - Create Service Project (WCF)
I created a service project which returns Data.

IService Method

    #region---Get Offers For Browser App---
    [OperationContract]
    [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    List<sp_GetOffersForBrowserApp_Result> GetOffersForBrowserApp(string URL);
    #endregion

Service Method
    #region---Get Offers For Browser App---
    public List<sp_GetOffersForBrowserApp_Result> GetOffersForBrowserApp(string URL)
    {
        return Offers.Instance.GetOffersForBrowserApp(URL);
    }
    #endregion

Step 2- Content Script


// ==UserScript==
// @name content
// @include http://*
// @include https://*
// @require jquery-1.9.1.min.js
// ==/UserScript==


var $ = window.$.noConflict(true); // Required for IE

function postPageInfoMessage() {   
    RenderFonts();
    var pageInfo = {
        url: document.URL
    };

    kango.console.log('Sending page info...');

    // dispatch messsage to background script
    kango.dispatchMessage('PageInfo', pageInfo);
}

postPageInfoMessage();


function GetAlertHTML(Offer) {       
   var rType = "";
    rType += "<div id=\"divCO\" style=\"z-index:999999999999999 !important;background-color:#fcfbfb; box-shadow:0px 0px 15px 5px rgba(0,0,0,.4); padding:20px; min-height:100px; width:380px; position:absolute; top:10px; right: 25px; font-family: 'Open Sans', sans-serif; border-radius:4px\">";
    rType +="   <a  class=\"tcb_close\" href=\"#\" style=\"position:absolute; right:-9px; top:-7px\"><img src=\""+SiteURL+"/Img/close-icon-browserapp.png\" width=\"27\" height=\"27\" /></a>";
    rType +="   <div style=\"border:solid 1px #ccc; background-color:#fff; width:100px; height:70px; float:left; box-shadow:0 10px 10px -5px rgba(0,0,0, .3); margin-top:5px\">";
    rType += "    <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
    rType +="       <tr>";    
    rType +="        <td style=\"height:70px; text-align:center\"> <img src=\""+Offer.MerchantLogoURL+"\" width=\"86\" height=\"39\" alt=\""+Offer.MerchantName+"\" /> </td>";
    rType +="       </tr>";
    rType +="     </table>";
    rType +="   </div>";
    rType +="   <div style=\"margin-left:120px; font-size:15px; margin-right:10px\">";
    rType +="   <p style=\"margin:0;  line-height:18px\">";
    rType +=    (Offer.Description.length>150?Offer.Description.substring(0,120)+"...":Offer.Description);
  
    rType +="   </p>";   
    rType +="    <a target=\"_blank\" href=\""+Offer.SiteURL+"/"+EncodeTextForURL(Offer.MerchantName)+"?O="+Offer.ID+"\" style=\"background-color:#f46300; border-radius:4px; padding:0px 20px 0 35px; color:#fff; text-decoration:none; display:inline-block; margin-top:20px; line-height:35px; height:35px; position:relative\"><img src=\""+SiteURL+"/Img/arrow-browserapp.png\" style=\"position:absolute; left:20px; top:12px\" alt=\"\" /> "+(Offer.TypeID==1?"Get Coupon":"Get Discount")+"</a>";
    
    rType +="   </div>";
    rType += "</div>";
    return rType; 
}



var AlertOffers;
var refreshInterval;
var SiteURL='http://mysite.com';
// handle messages from background script
kango.addMessageListener('ShowDiscountAlert', function (event) {   
    AlertOffers = event.data.GetOffersForBrowserAppResult;
    ShowCOAlert();
    refreshInterval =  setInterval(function () { ShowCOAlert() }, 15000);

});

function ShowCOAlert() {   
    if (AlertOffers.length > 0) {
        $('body').append(GetAlertHTML(AlertOffers[0]));
        $('.tcb_close').click(function()
        {
         if ($('#divCO').length > 0) {
             $('#divCO').remove();
          }
        })
        setTimeout(function () {
            if ($('#divCO').length > 0) {
                $('#divCO').remove();
            }
        }, 8000)
        AlertOffers.shift();
    }
    else
    {
        clearInterval(refreshInterval);
    }

}

Step 3- Main script


function getURLFromPageInfo(info) {
    return 'Url: ' + info.url;
}

function getDomainFromUrl(url) {
    var matches = url.match(/:\/\/(.[^/]+)/);
    return ((matches != null && typeof matches[1] != 'undefined') ? matches[1] : null);
}

var getQueryString = function (field, url) {
    var href = url;
    var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
    var string = reg.exec(href);
    return string ? string[1] : null;
};

function COExtension() {
    var self = this;
    kango.ui.browserButton.setPopup({url:'popup.html', width: 600, height:520})
    //kango.ui.browserButton.addEventListener(kango.ui.browserButton.event.COMMAND, function () {
        //self._onCommand();
    //});
}


kango.addMessageListener('PageInfo', function (event) {
    // is message from active tab?
    kango.console.log('Page info received\nTarget tab url=' + event.target.getUrl());
    if (event.target.isActive()) {
        var domain = getDomainFromUrl(getURLFromPageInfo(event.data));

       
        var details = {
            url: ServiceUrl,
            method: 'GET',
            contentType: 'json',
            params:{'URL': domain} 
        };

          kango.xhr.send(details, function(data) {
            if (data.status == 200 && data.response != null) {
                kango.console.log('Data Found domain is: ' + domain);
                if(data.response.GetOffersForBrowserAppResult.length!=0)
                {
                   event.target.dispatchMessage('ShowDiscountAlert',data.response);
                }
            } 
        });
       
        }    
});

var ServiceUrl='http://mydomain.com/services/MyService.svc/GetOffersForBrowserApp';
Above script will send URL details to the server using WCF Service & Service will respond data of related offers on given website.

 Step 3- Build Extension
Build extension from following command.
python kango_dir/kango.py build "path/to/MyExtension"

Now Install on chrome & test on browser.


0 comments :

Post a comment

  • Popular Posts
  • Comments