Sharepoint WopiFrame allow framing

In Sharepoint you can use <WebPartPages:AllowFraming runat="server" /> to disable the SAMEORIGIN for X-FRAME-OPTION giving you the opportunity to call your page from an iframe (see this other article).

However you cannot use the same trick to preview a file into the browser with WopiFrame.aspx. But there is a way to do it, using the parameters into the URL.

Let’s say the url to preview your document is:
https://my.company.com/sharepoint/_layouts/15/WopiFrame.aspx?sourcedoc=/files/Demo.docx&action=default

You need to replace action=default with action=embedview, AND you need to call WopiFrame2.aspx instead of WopiFrame.aspx (which will lead to a Something Went Wrong - Sorry, you don't have access to this page).

So the URL to use for your iframe will be:
https://my.company.com/sharepoint/_layouts/15/WopiFrame2.aspx?sourcedoc=/files/Demo.docx&action=embedview

Change a « Choice with Fill-In » field into a magic dropdown [Sharepoint]

Sometimes you want to modify the options for a dropdown box by removing some existing options, however you want to be able to keep these old values for reporting or whatever reasons.

Below is a way to do it by using jQuery and SharepointPlus. It will hide the « Specify your own value » stuff, and add the old value (if any) into the dropdown selection.

For example if you have a Choice field with options « A », « B », « C ». Your item ID #1 has value « B ».
After a while you decide to delete « B » and add « D », but you want to be able to find items with the « B » value.
So you choose « Choice with Fill-In » and apply the below code:

// For flexibility reasons we create them as a Choice with Fill-In option,
//    however we hide the free text field and we show only the dropdown
//    in case of the fill-in has a value, then we add it into the list of options
$SP().formfields(["My Fist Dropdown", "Another One"]).each(function() {
  var $e = this.elem();
  // hide all except the dropdown
  //$e.not('select').hide().filter(':radio:last').closest('tr').hide(); // SP2010
  $e.eq(0).closest('table').find('tr:gt(0)').hide(); // SP2013
  // if we have a value into the fill-in box, then:
  //   - add it into the options
  //   - when another value is selected we check the first checkbox
  var fillValue = $e.last().val();
  if (fillValue) {
    $e.filter('select').append('<option data-fillin="true">'+fillValue+'</option>').each(function() {
      var $this=$(this);
      $this.find('option:last').prop("selected", true);
      $this.removeAttr("onclick").on('change', function(event) {
        var $opt = $(this).find(':selected');
        if ($opt.data("fillin")) {
          $e.filter(':radio:last').prop("checked", true);
        } else {
          $e.filter(':radio:first').prop("checked", true);
        }
      });
    });
  }
})

So now, if you create a new item you’ll see a dropdown with « A », « C », and « D » only.
But if you edit your item #1, you’ll have a dropdown with « A », « C », « D » and « B ».

Trigger an event when a file is uploaded on Sharepoint 2013 by drag and drop

If you want to trigger an event after a drag&drop a file for an upload operation on Sharepoint, then you’ll have to add some JavaScript into your page.

// we need to make sure sp.core.js is loaded
SP.SOD.executeOrDelayUntilScriptLoaded(function() {
  window.UploadFinishFunc=function(b, a) {
    typeof g_currentControl.postUploadFunc == "function" && a.status != UploadStatus.CANCELLED && g_currentControl.postUploadFunc(a.files);
    a.status != UploadStatus.CANCELLED && myPostUploadFunc(a);
    g_currentControl.status = ControlStatus.UPLOADED;
    UpdateProgressBar(ProgressMessage.UPLOADED, a);
    RefreshResult(a);
    g_currentControl.status = ControlStatus.IDLE
  }
}, 'sp.core.js');
SP.SOD.executeFunc('sp.core.js')

// below is the function that will be called
function myPostUploadFunc(data) {
  console.log("myPostUploadFunc => ",data)
}

Adding a custom action to a callout in SharePoint 2013

This article has been VERY useful. But I wanted something lightly different: I wanted to add a custom action, but also have the « EDIT » button (but not the « SHARE »), and to use the current item info for my custom action.

Here is the result:

// source: https://www.eliostruyf.com/adding-a-custom-action-to-a-callout-in-sharepoint-2013/
// add a special callout action for our library
SP.SOD.executeFunc("callout.js", "Callout", function () {
  var itemCtx = {};
  itemCtx.Templates = {};
  itemCtx.BaseViewID = 'Callout';
  // Define the list template type
  itemCtx.ListTemplateType = 101;
  itemCtx.Templates.Footer = function (itemCtx) {
    // context, custom action function, show the ECB menu (boolean)
    return CalloutRenderFooterTemplate(itemCtx, AddCustomAction, true);
  };
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});

function AddCustomAction (renderCtx, calloutActionMenu) {
  var itemIndex = renderCtx.CurrentItemIdx
  // Add your custom action
  calloutActionMenu.addAction(new CalloutAction ({
    text: "Custom Action",
    tooltip: 'This is your custom action',
    onClickCallback: function() {
      // all the data related to your item are into `renderCtx.ListData.Row[itemIndex]`
      console.log('Callback from custom action');
    }
  }));
  // re-add EDIT action
  calloutActionMenu.addAction(new CalloutAction ({
    text: "Edit",
    onClickCallback: function(event) {
      // use the default action we have when clicking on the filename into the library
      // or call the EditForm if it's a list item and not a library
      DispEx(this, event,'TRUE','FALSE','FALSE','SharePoint.OpenDocuments.3','1','SharePoint.OpenDocuments','','1https://your.sharepoint.com/_layouts/15/WopiFrame.aspx?sourcedoc='+renderCtx.ListData.Row[itemIndex].FileRef+'&action=default','','1','0','0','0x7fffffffffffffff')
    }
  }));
}

How to hide the left navigation bar in Sharepoint without CSS

We can easily find some workarounds to hide the left navigation bar on Sharepoint using CSS…. But I wanted to remove it on a specific page, without using any CSS.

It’s actually pretty simple. You need to add the below tag into your .aspx page:

<asp:Content ContentPlaceHolderID="PlaceHolderLeftNavBar" runat="Server"></asp:Content>

Tested with Sharepoint 2013 On-Promise.

How to cache the CSS Fonts with Sharepoint

If you use your own CSS file with your own CSS fonts, then we’ll notice that Sharepoint doesn’t send cache headers if you use the below CSS code:

@font-face {
  font-family: 'Roboto';
  src: url('/_catalogs/masterpage/css/fonts/Roboto/Regular/Roboto-Regular.woff2') format('woff2'),
       url('/_catalogs/masterpage/css/fonts/Roboto/Regular/Roboto-Regular.woff') format('woff'),
       url('/_catalogs/masterpage/css/fonts/Roboto/Regular/Roboto-Regular.ttf') format('truetype');
  font-weight: 400;
  font-style: normal;
}

To have this resource sent back from the Sharepoint server with cache headers, you just need to add ?ctag=0 at the end:

@font-face {
  font-family: 'Roboto';
  src: url('/_catalogs/masterpage/css/fonts/Roboto/Regular/Roboto-Regular.woff2?ctag=0') format('woff2'),
       url('/_catalogs/masterpage/css/fonts/Roboto/Regular/Roboto-Regular.woff?ctag=0') format('woff'),
       url('/_catalogs/masterpage/css/fonts/Roboto/Regular/Roboto-Regular.ttf?ctag=0') format('truetype');
  font-weight: 400;
  font-style: normal;
}

Create an Unpublished Content view for the masterpage galery [Sharepoint]

With Sharepoint 2013 I wanted an easy way to list of the pages in my masterpage galery that haven’t been published yet.

You first need to Create a new view named Unpublished Content. You can sort by Name, and scroll down to the Folders settings and choose Show all items without folders.

We now have all our files in the view.

Next, switch to the Library ribbon and choose Modify in SharePoint Designer (Advanced) from the Modify View dropdown.

Sharepoint Designer will open your page.

In Sharepoint Designer, switch to the Home tab and choose Advanced Mode. The file is reloaded.

Search into your code the tag ListViewXml. On this line you should have &lt;Query;&&gt;. Just after it, we need to add:
&lt;Where&gt;&lt;Or&gt;&lt;Eq&gt;&lt;FieldRef Name="_ModerationStatus" /&gt;&lt;Value Type="ModStat"&gt;Draft&lt;/Value&gt;&lt;/Eq&gt;&lt;IsNotNull&gt;&lt;FieldRef Name="CheckoutUser" /&gt;&lt;/IsNotNull&gt;&lt;/Or&gt;&lt;/Where&gt;

Before:

After:
(click to enlarge)

Save, and your view should only show the unpublished content!

(Article inspired by https://thechriskent.com/2013/02/14/unpublished-view/)

Trigger an event when an element is visible in a scrollable area [JavaScript]

EDIT in 2022

It might also be interesting to look at Intersection Observer that is now available in most browsers, and there is also a polyfill.

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    let isVisible=(entry.intersectionRatio===1);
  });
}, {threshold:1});
observer.observe(document.querySelector('#element');

END EDIT

I have this specific need that is to trigger an event when an element becomes visible/invisible into a scrollable area. Here is the code I came to:

/**
 * Create the handler
 * @param {NodeElement} holder The scrollable area to monitor (where the 'scroll' event will be apply)
 */
var VisibleEventListener = function(holder) {
  var _this=this;
  _this.started = false;
  _this.holder = holder;
  // detect if an element is visible
  _this.isScrolledIntoView=function(el) {
    var bndElem = el.getBoundingClientRect();
    var bndHolder = _this.holder.getBoundingClientRect();
    return bndElem.top <= bndHolder.top ? !(bndHolder.top - bndElem.top > bndElem.height) : !(bndElem.bottom - bndHolder.bottom > bndElem.height);
  }
  // permits to deal with the scroll
  _this.scrollHandler=function(e) {
    for (var i=0, len=_this.events.length; i<len; i++) {
      _this.events[i].check();
    }
  }
  _this.events=[];
}
/**
 * Add the visible/invisible event for an element into a scrollable area
 * @param {NodeElement}   element  The element to test
 * @param {String}   listener 'visible' or 'invisible'
 * @param {Function} callback The callback function to be called when the event is triggered
 */
VisibleEventListener.prototype.add = function(element, listener, callback) {
  var _this=this;
  var ElementToMonitor=function(element, listener, callback) {
    this._super=_this;
    this.element=element;
    this.isVisible=false;
    this.callback=callback;
    this.listener=listener;
  }
  ElementToMonitor.prototype.check = function() {
    var visible=this._super.isScrolledIntoView(this.element);
    if (visible && !this.isVisible) { // becomes visible
      this.isVisible=true;
      if (this.listener==='visible') this.callback.call(this.element)
    } else if (!visible && this.isVisible) { // becomes invisible
      this.isVisible=false;
      if (this.listener==='invisible') this.callback.call(this.element)
    }
  };
  var etm=new ElementToMonitor(element,listener,callback);
  _this.events.push(etm);
  // if we have started to monitor
  if (_this.started===true) etm.check();
}
VisibleEventListener.prototype.start = function() {
  this.holder.addEventListener('scroll', this.scrollHandler);
  this.started = true;
  // trigger the check to verify if the elements are already visible
  this.scrollHandler();
}
VisibleEventListener.prototype.stop = function() {
  this.holder.removeEventListener('scroll', this.scrollHandler);
  this.started = false;
}

And to use it:

// initiate our area with VisibleEventListener
var vel = new VisibleEventListener(document.querySelector('#s4-workspace'));
// add the elements to monitor
vel.add(document.querySelector('.slideshow'), 'invisible', function() {
  console.log(this,' is now invisible')
})
vel.add(document.querySelector('.slideshow'), 'visible', function() {
  console.log(this,' is now visible')
})
// start the monitoring
vel.start();