How to open files/documents in SharePoint document library is new tab

As you know documents in SharePoint document library (images, pdf files etc) always opens in the same page and it leaves you from the SharePoint context. You can not go back to SharePoint from that page unless you press the back button of your browser.

Here is a fix/workaround for this problem. Put below code to a js file and refer this file in your master page.

 try {
     
        //Below code is for opening document library files(pdf,jpg) in new tab
        // has to be on an interval for grouped doc libraries
        // where the actual links are loaded only once a group
        // is expanded
        setInterval(
          function () {
              $("a[onclick*='return DispEx'][target!='_blank'][aria-label$='pdf File'],a[onclick*='return DispEx'][target!='_blank'][aria-label$='jpg File']")
                .attr("target", "_blank")
                .removeAttr("onclick");
              // document type icons
              $("td.ms-vb-icon>img[onclick]:not([documentUrl])")
                .click(function (e) {
                    window.open($(this).attr("documentUrl"), "_blank");
                    e.stopPropagation();
                    e.preventDefault();
                    return false;
                })
                .each(function () {
                    $(this).attr(
                    "documentUrl",
                    $.trim(String($(this).attr("onclick"))
                      .split("=")[1]
                      .replace(/["'{}]/g, "")
                      .split(";")[0])
                    );
                    this.onclick = null;
                });
          },
          500
        );
    } catch (e) {
    }

As you can see the above code works for all the document libraries and only for below file type:

  • PDF
  • jpg 
Since the ms-office file always opens in the office application or it downloads to the machine, we do not need to add them here. You can modify this code for png or any other types.


If this post was helpful to you, please consider visiting one or more advertisements on the page.Writing detailed post takes time, patience and advertising revenue helps to offset the effort.

Comments

Popular posts from this blog

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

SharePoint 2013 REST API Reference

Simple Risk Assessment Matrix table with resultant risk calculation

Kendo UI (Core JavaScript) grid Server Paging, Server Sorting and Server Filtering with Dynamic SQL queries

Sharepoint- Using an Image From formatmap32x32.png in a Ribbon Control