another technical blog...technically

Sunday, November 27, 2016

Trust no one: especially about SharePoint Search

Some days ago, the customer said he want to be able to search files in OneDrive using O365 search.
The solution is there: https://technet.microsoft.com/en-us/library/dn627526.aspx
After Step 5, i went into the search site, selecting OneDrive result source, and i run the search with no parameter... wow only OneDrive results; after that i tried another search with a word and... surprise surprise... results from everywhere.
After lot of hours of tentatives, the decision was to filter results again also in the query text of the search web part (path:https:// tenant_name -my.sharepoint.com/personal), in order to mantain mental sanity.
Share:

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:

Me, myself and I

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