another technical blog...technically

Sunday, November 27, 2016

Customize search results "without" display templates in O365

I know, the blog post is provocatory, but, i mean, if you have to modify something on default search results you'll probably say:
"hey this is a no problem, we can modify display templates"
Ok..ok that's true, but if i have to inject something in all results display templates, you'll probably know there are tons of those display templates, so you would prefer not to touch those templates.
Sometimes you got to take the left-hand-way, so i noticed in the search subsite, that O365 load this javascript namespace Srch.
I've also found an article where the author did something similar (but i cannot find it anymore).
function hookScript() {
    if (typeof Srch !== "undefined" && typeof Srch.Result !== "undefined") {

  // Save the original function somewhere else
        Srch.Result.prototype.originalRender = Srch.Result.prototype.render;
  
  // Substitute the original function with something more comples
        Srch.Result.prototype.render = function () {
            
   // Here we can do something before rendering results
   
            this.originalRender();

   // Here we can add custom code as we wish after results render
   // In the example below i cycle amond search results doing things
            var results = jQuery(".ms-srch-item-path");

            jQuery.each(results, function(index, value) {
                ...
            });
        };
    };
}

// It's clear you'll need to execute the hook script after body it's loaded
ExecuteOrDelayUntilBodyLoaded(function () {
    hookScript();
});
Another trick it's to use Srch to override other functions. For example, a typical customer request is the change of the icon in SharePoint results.
Here you can work every display templates or do something more generic:
jQuery(document).ready(function () {

    if (typeof Srch !== "undefined" && typeof Srch.U !== "undefined") {
        Srch.U.getIconUrlByFileExtension = function(ctxCurrentItem) {
            return CustomFunction(ctxCurrentItem);
        }
    }
});
Enjoy ;)
Share:
written in: Milano, Italia

0 commenti:

Post a Comment

Because of a lot of SPAM about courses, I need to moderate all comments here.
I ensure you that I will answer whenever possible (if you are not a spammer).

Me, myself and I

My Photo
I'm just another IT guy sharing his knowledge with all of you out there.
Wanna know more?