Forum Discussion

Venkata Ratnam Vemula's avatar
Venkata Ratnam Vemula
Copper Contributor
Oct 16, 2017

Use pnp js to query other sharepoint sites using Plain Javascript

I am trying to query a document library from a other sharepoint site (Not a Subsite) in the same tenant, but not able to find a way

I can query as follows to retrieve from the current sharepont site context. Is it possible to query from other sharepoint sites using pnp js?

var deferred = $.Deferred();
   $pnp.sp.web.lists.getByTitle('Doc List').items.filter("AuthorId eq '" + _spPageContextInfo.userId + "'").get().then(function (results) {
       deferred.resolve(results);
   });

 

2 Replies

  • If the site (SPWeb on the other site collection) is with the same hostname it can be requested.

    A web object should be created using `let web = new pnp.Web('https://host/sites/site/web')`. Web absolute path should be passed as a parameter when creating a new web object instance.

     

    $pnp object is a global shim. In the examples, it's more usual to meet `pnp`.

     

    Also, in the code sample above, the logic will fail because UserId for the same user is different on the different site collections, UserId can be requested with `web.currentUser`.

     

    And yet another piece of advice, as PnP JS Core already deal with promises you do not need to wrap it with jQuery deferred and can return native ES6 promises.

     

    Please check the code sample in TypeScript:

    import { Web } from 'pnp';
    
    let getUserItemsFromAnotherWeb = (webAbsoluteUrl: string, listName: string): Promise<any> => {
      let web = new Web(webAbsoluteUrl);
      return web.currentUser.get()
        .then(u => {
          return u.Id;
        })
        .then(userId => {
          return web.lists
            .getByTitle(listName).items
            .filter(`AuthorId eq '${userId}'`).get();
        });
    };

    and in ES5, if you really need a vanilla JS for any reasons:

    var getUserItemsFromAnotherWeb = function(webAbsoluteUrl, listName) {
      var web = new $pnp.Web(webAbsoluteUrl);
      return web.currentUser.get()
        .then(function(u) {
          return u.Id;
        })
        .then(function(userId) {
          return web.lists
            .getByTitle(listName).items
            .filter('AuthorId eq "' + userId + '"').get();
        });
    };

     

    Oh, and final thing getting lists by title (`web.lists.getByTitle`) can cause none valid code if a list can be renamed. I would recommend getting lists with `web.getList('_list_relative_uri_')`.

     

    Hope this help. 

     

Resources