How to Build Reusable Web Components Using Stencil.js

How to Build Reusable Web Components Using Stencil.js

[Stencil](https://stenciljs.com/ "Stencil") is a compiler for generating web components developed by the [Ionic team](https://ionicframework.com/team "Ionic team"). Web components in Stencil can be used as standalone components, as a part of a...

Stencil is a compiler for generating web components developed by the Ionic team. Web components in Stencil can be used as standalone components, as a part of a Stencil web application, and as part of Ionic progressive web applications.

According to the Ionic team, Stencil should not be called a framework, but it looks like a framework to me :).

A web component (in case you missed it) is nothing more than a custom HTML tag () packed with additional logic written in JavaScript.

Components in Stencil are written in TypeScript and then compiled into various versions of JavaScript. Various bundles produced by a compiler are meant to be used in different scenarios. Everything is covered, from older browsers with polyfills to the newer ones with all of the shiny JavaScript features included. It is the same as Differential Loading in Angular.

Stencil looks like a mixture of React and Angular. Developers from both teams will find many familiar concepts and keywords, and because of that, learning Stencil should be easy-peasy.

In this introductory example, we can spot a component decorator with a render method using JSX.

import { Component, Prop, h } from '@stencil/core';

@Component({
  tag: 'my-first-component',
})
export class MyComponent {

  // Indicate that name should be a public property on the component
  @Prop() name: string;

  render() {
    return (
      <p>
        My name is {this.name}
      </p>
    );
  }
}

And the Prop is similar to the Input tag in Angular.

Stencil:
  • Can be combined with all major front-end frameworks, as well as with other JavaScript libraries or with no library at all

  • It does not require run-time (like Angular, React, Vue…). A produced JavaScript bundle is all that is needed in order for it to be used

  • It is fully aligned with the implementation of Custom Elements v1

  • Production bundle size start from ~100 kb and with polyfills ~133 kb (we can gzip it)

Browser support

In general, web components (and Stencil) are supported across all major browsers. They’re only not supported by Edge versions from 12 to 18 (that is before the WebKit implementation). Anyway, it is only 2% of all used browsers in the world.

The main user of Stencil is Ionic framework and all it’s UI components are built using Stencil. Go through a few of them, from the previous link, see how they did it. Reading quality code can be a great way to learn

Getting started

Stencil provides great tooling out of the box. It comes with an integrated development server, a generator for components, a compiler for all sorts of bundles, a doc generator, and a testing suite.

Prerequisites

We have to install the latest LTS version of Node and NPM in order to work with it. You should validate what you have first with:

node -v
npm -v

Ensure that we have Node.js ≥ 12 and NPM version ≥ 6.

We have to install Stencil as a global package:

npm install -g stencil

Extensions of components are TSX because it uses JSX as a templating language.

Now, if we want to generate our project, we will have to use an interactive wizard provided by Stencil trough NPM init:

npm init stencil

To demonstrate its usage, let’s build a simple cryptocurrency widget.

We want to build a reusable component so we will choose the third option, component.

And after a few seconds you should see:

Creating a component

First, we will remove the generated component my-component from the code. Feel free to delete it.

After, using npm run generate, we will generate our first component:

It’s important that our component has a name with a dash. In our case, it is crypto-view. This will be the name of our custom HTML tag .

Manually, we have to replace references from my-component to crypto-view in src/index.html in order to get the development server working again:

This is what our generated component looks like:

import { Component, Host, h } from '@stencil/core';

@Component({
  tag: 'crypto-view',
  styleUrl: 'crypto-view.css',
  shadow: true
})
export class CryptoView {

  render() {
    return (
      <Host>
        <slot></slot>
      </Host>
    );
  }

}

Immediately we can spot in our @Component decorator setting shadow: true. It’s very important that our main (entry ) component has this setting. Basically, it means that this element will be isolated from the rest of the DOM in our page with the shadow root:

It further means that styles defined in crypto-view.css will not be applied to any element outside of the crypto-view component.

In the render method we have:

render() {
  return (
    <Host>
      <slot></slot>
    </Host>
  );
}

Host , as its name implies, refers to a host component. In our case, it is the element. Check out this quick example:

render() {
  return (
    <Host class={'hello'}>
      <slot></slot>
    </Host>
  );
}	
	

This will append class hello on crptyo-view component.

![This is image title](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/10/hello.png?w=643&ssl=1 "This is image title")	

*Class hydrated is added by Stenci *

In JSX we must have root (wrapping ) element. By default, it is Host in Stencil, but it can be DIV as well.

Among Host, we have slot. If you are coming from the Angular ecosystem, slot is ng-content. It will project any content passed between … tags. We can pass HTML, child components or text, and it will be projected on the place we define .

We can have multiple slots as well, take a look at this example:

<ui-component>
  <p slot='my-title'>Title</p>
  <p slot='my-description'>Description</p>
</ui-component>	
	

It can be rendered using the name attribute in slot:

render () {
  return (<div>
    <slot name='my-title' />
    <slot name='my-description' />
  </div>)
}	
	
CSS

Now let’s open the CSS file crypto-view.css:

:host {
  display: block;
}	

We will see that only :host is defined. Similar to the Host element in JSX code, :host refers to a host component , which has default display: block. Note that the majority of elements in HTML have display: block. Now when this is set, we can apply any CSS style to a host element through :host directive.

Props (attributes)

As we have to fetch crypto data from somewhere, we will use API from cryptocompare.com as it offers usage with free API Key.

The first prop that we will define will be apiKey. Prop names with camel case resolve to two words with a dash in between, because camel case is not supported in HTML, while in JSX it is supported.

![This is image title](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/10/prop.png?w=766&ssl=1 "This is image title")

And in our component:

import { Component, Host, h, Prop } from '@stencil/core';

@Component({
  tag: 'crypto-view',
  styleUrl: 'crypto-view.css',
  shadow: true
})
export class CryptoView {

  /**
   * Valid API key obtained from cryptocompare.com
   */
  @Prop() apiKey: string;

  componentDidLoad() {
    console.log(this.apiKey);
  }

  render() {
    return (
      <Host>
        <slot></slot>
      </Host>
    );
  }

}	
Lifecycle methods (Hooks)

Notice the componentDidLoad function, and console.log in it. If we run the application now, we will see our apiKey logged in the console.

Class method componentDidLoad is a lifecycle hook. Which means that it is triggered at a defined point in the life of the component. Developers from a React background will recognize the name.

Here are some commonly used Hooks ( lifecycle methods in Stencil ):

  • componentWillLoad() is triggered before rendering

  • componentDidLoad() is triggered after rendering ( inserting into the DOM)

  • componentWillUpdate() is triggered before updating

  • componentDidUpdate() is triggered after updating

  • componentDidUnload() is triggered after unmounting ( removing from the DOM)

We can find the full list and explanation on Stencil doc page for Lifecycle Methods.

In our case, as the apiKey is not asynchronously set we can use the
componentDidLoad Hook to get its value and call the API. Note that
componentDidLoad is called only once, while some lifecycle methods can be called multiple times.

We will create, in src/utils/utils.ts , the function getCryptoData which will fetch the latest price in USD and EUR for Bitcoin, Etherum, and Ripple.

import { CryptoInterface } from '../components/crypto-view/crypto.interface';

export function getCryptoData(apiKey: string): Promise<CryptoInterface> {
  return fetch(`https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,XRP&tsyms=USD,EUR&api_key=${apiKey}`)
    .then(response => response.json());
}	
	

The response from the API is mapped to the interface in order to get typing support from the IDE ( in my case it is WebStrom).

export interface CryptoInterface {
  BTC: IPrices;
  ETH: IPrices;
  XRP: IPrices;
}

interface IPrices {
  USD: number;
  EUR: number;
}	
State

Response from the server is stored in the variable cryptoData which is decorated by @State.

import { Component, Host, h, Prop, State } from '@stencil/core';
import { getCryptoData } from '../../utils/utils';
import { CryptoInterface } from './crypto.interface';

@Component({
  tag: 'crypto-view',
  styleUrl: 'crypto-view.css',
  shadow: true
})
export class CryptoView {

  /**
   * Valid API key obtained from cryptocompare.com
   */
  @Prop() apiKey: string;

  @State() cryptoData: CryptoInterface;

  componentDidLoad() {
    getCryptoData(this.apiKey).then((data) => {
      this.cryptoData = data;
    });
  }

  render() {
    return (
      <Host>
        <slot></slot>
      </Host>
    );
  }

}	
	

Each change on a variable is annotated with the decorator State which will trigger the re-rendering of the component. It is the same as in React. In Angular, it is a different (and much longer) story.

In React, setting state is done with the internal method setState, which is equal to assigning value to the cryptoData variable in Stencil ( it is not a normal variable, it is state variable ).

In our case, we asynchronously get crypto data, and upon receiving it in the component, we assign it to the state variable cryptoData.

To present data, we will create another component called crypto-table:

The crpyto table is a presentational component. Such a component only receives things through props and displays them into JSX. No internal state, no local computations and etc.

It looks like this:

import { Component, Host, h, Prop } from '@stencil/core';

import { CryptoInterface } from '../crypto-view/crypto.interface';

@Component({
  tag: 'crypto-table',
  styleUrl: 'crypto-table.css',
  shadow: false,
  scoped: true
})
export class CryptoTable {

  @Prop() cryptoData: CryptoInterface;
  @Prop() cryptoCurrencies: string[];

  render() {
    return (
      <Host>
        <table class={'crypto'}>
          <tr>
            <td></td>
            <td>USD</td>
            <td>EUR</td>
          </tr>
          {this.cryptoCurrencies.map((item) => {
            return this.cryptoData && item in this.cryptoData ? <tr>
              <td>{item}</td>
              <td>{this.cryptoData[item].USD}</td>
              <td>{this.cryptoData[item].EUR}</td>
            </tr> : null
          })}
        </table>
      </Host>
    );
  }

}	

Now, if you are familiar with React, Stencil uses JSX and the same principles for displaying data. If you come from Angular, forget about ngIf and ngFor directives, get used to JSX as soon as possible.

In this component, we will set shadow to false, as we don’t need to isolate this component further in the DOM. The new setting here is scoped: true, which adds additional CSS classes to each element in this component ( cs-crypto-table ):

A combination of scoped and shadow attributes in the component decorator from Stencil are similar to ViewEncapsulation in Angular.

For creating dumb ( presentational ) components, we can use Functional Components approach. They are arrow functions that accept props as a parameter and return JSX.

In the CryptoView component we will inject CryptoTable and pass data through props bindings:

import { Component, Host, h, Prop, State } from '@stencil/core';
import { getCryptoData } from '../../utils/utils';
import { CryptoInterface } from './crypto.interface';

@Component({
  tag: 'crypto-view',
  styleUrl: 'crypto-view.css',
  shadow: true
})
export class CryptoView {

  /**
   * Valid API key obtained from cryptocompare.com
   */
  @Prop() apiKey: string;

  @State() cryptoData: CryptoInterface;

  cryptoCurrencies = ['BTC', 'ETH', 'XRP'];

  componentDidLoad() {
    getCryptoData(this.apiKey).then((data) => {
      this.cryptoData = data;
    });
  }

  render() {
    return (
      <Host>
        <b>Crypto data on date: {new Date().toLocaleDateString()}</b>
        <crypto-table cryptoData={this.cryptoData} cryptoCurrencies={this.cryptoCurrencies} />
        <slot></slot>
      </Host>
    );
  }

}	
	

Note that we didn’t have to import CryptoTable anywhere, that is all done by the Stencil compiler.

I grabbed CSS from W3school, and our crypto table looks something like this:

Methods

If we imagine a scenario where the host application wants to refresh crypto data in our component. We must somehow expose method which will trigger re-fetching crypto data.

Stencil introduced the Method decorator for that purpose:

@Method()
async refreshCryptoData() {
  getCryptoData(this.apiKey).then((data) => {
    this.cryptoData = data;
  });
}	

The exposed class method must be marked as an async function. It is a requirement by Stencil.

Now, in index.html we can call it with:

<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
  <title>Stencil Component Starter</title>

  <script type="module" src="/build/crypto-widget.esm.js"></script>
  <script nomodule src="/build/crypto-widget.js"></script>

</head>
<body>
    <crypto-view api-key="fd937be4428d64cf4dd1b51146aef28e46d224aea7ea5bdfbbb6d296a05ec1a9"></crypto-view>

    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            const cryptoView = document.querySelector('crypto-view');
            setTimeout(() => {
                cryptoView.refreshCryptoData();
            }, 2000);
        })
    </script>
</body>
</html>	
	

For the sake of the demo, we are waiting for two seconds and then calling method to refresh crypto data in our component.

Events

In Stencil, events are similar to Output in Angular where child component can emit something, and parent component can catch that. Events are used to push data from child components to parent components. That is similar to what we do every day in Angular and React.

There are two ways of catching events. One with an attribute on the component and the second one with Listen decorator.

First, let’s try to notify the parent component from the child component:

Here is the code:

import { Component, Host, Event, h, EventEmitter } from '@stencil/core';

@Component({
  tag: 'crypto-refresher',
  styleUrl: 'crypto-refresher.css',
})
export class CryptoRefresher {

  @Event() refreshCryptoData: EventEmitter;

  refresh() {
    this.refreshCryptoData.emit(true);
  }

  render() {
    return (
      <Host>
        <button onClick={() => this.refresh()}>Refresh Crypto Data</button>
      </Host>
    );
  }

}	
	

Our refreshCryptoData is decorated with the Event decorator ( don’t forget to import it from @stencil/core ) and then emitted upon clicking on the button.

import { Component, Host, h, Prop, State, Method, Listen } from '@stencil/core';
import { getCryptoData } from '../../utils/utils';
import { CryptoInterface } from './crypto.interface';

@Component({
  tag: 'crypto-view',
  styleUrl: 'crypto-view.css',
  shadow: true
})
export class CryptoView {

  /**
   * Valid API key obtained from cryptocompare.com
   */
  @Prop() apikey: string;

  @State() cryptoData: CryptoInterface;

  cryptoCurrencies = ['BTC', 'ETH', 'XRP'];

  componentDidLoad() {
    this.fetchData();
  }

  fetchData() {
    getCryptoData(this.apikey).then((data) => {
      this.cryptoData = data;
    });
  }

  @Method()
  async refreshCryptoData() {
    this.fetchData();
  }

  @Listen('refreshCryptoData')
  listen(event) {
    console.log(event)
  }

  render() {
    return (
      <Host>
        <b>Crypto data on date: {new Date().toLocaleDateString()}</b>
        <crypto-table cryptoData={this.cryptoData} cryptoCurrencies={this.cryptoCurrencies} />
        <crypto-refresher onRefreshCryptoData={() => this.fetchData()} />
        <slot></slot>
      </Host>
    );
  }

}	

Notice that we use the shortened version of invoking component , it is the preferred way as we don’t project any data into it.

Let’s catch this event with an attribute on the component first.

In Stencil, we should name the attribute which catches our event with the prefix on. If our event is called, the attribute for catching it is onRefreshCryptoData. In our case, onRefreshCryptoData is an arrow function that will call the fetchData method.

In case we pass some data with the Event, we will have that data in arrow function parameters.

The second way to catch events is with the Listen decorator. It accepts the name of event as a parameter and calls the function bellow after catching it. The Listen decorator is handy when it comes to listening on system events like resize, scroll, etc. It is similar to HostListener in Angular.

Watch (reactivity)

Now, if want to listen on Props changes and call other methods or compute other things upon it, we have to use the Watch decorator.

If we, for example, want to compute the sum of prices in the crytpo table component and present that, we will have to wait for cryptoData to be fetched and passed, then compute the sum.

import { Component, Host, h, Prop, Watch, State } from '@stencil/core';

import { CryptoInterface } from '../crypto-view/crypto.interface';

@Component({
  tag: 'crypto-table',
  styleUrl: 'crypto-table.css',
  shadow: false,
  scoped: true
})
export class CryptoTable {

  @Prop() cryptoData: CryptoInterface;
  @Prop() cryptoCurrencies: string[];

  @State() sum: { USD: number, EUR: number };

  @Watch('cryptoData')
  watching(cryptoData: CryptoInterface) {
    this.sum = {
      USD: Math.round(cryptoData.BTC.USD + cryptoData.ETH.USD + cryptoData.XRP.USD),
      EUR: Math.round(cryptoData.BTC.EUR + cryptoData.ETH.EUR + cryptoData.XRP.EUR),
    }
  }

  render() {
    return (
      <Host>
        <table class={'crypto'}>
          <tr>
            <td></td>
            <td>USD</td>
            <td>EUR</td>
          </tr>
          {this.cryptoCurrencies.map((item) => {
            return this.cryptoData && item in this.cryptoData ? <tr>
              <td>{item}</td>
              <td>{this.cryptoData[item].USD}</td>
              <td>{this.cryptoData[item].EUR}</td>
            </tr> : null
          })}
          {this.sum ?
          <tr>
            <td></td>
            <td>{this.sum.USD}</td>
            <td>{this.sum.EUR}</td>
          </tr> : null }
        </table>
      </Host>
    );
  }

}				
				

In the example above, each time cryptoData is changed, the component will calculate the sum of all currencies.

Building and using

In order to build this project and produce shareable bundles, we have to run

npm run build				

The build will produce a dist folder and crypto-widget folder inside of it.

It’s safe to grab this folder and copy it to a place where we want to include our component.

In HTML it is enough to include two files, first one is crypto-widget.js, it is an es5 bundle (with polyfills) meant to be used in older browsers (IE 11).

The second one is crypto-widget.esm.js, it comes with all new JavaScript features like code-splitting, async-await, etc.

<script type="module" src="/build/crypto-widget.esm.js"></script>
<script nomodule src="/build/crypto-widget.js"></script>				
				

Browsers are smart today, and they will load only what they need.

Conclusion

Stencil is a great library. It is well developed, well documented, battle-tested, backed by a big company, aligned with standards, and is very easy to learn.

Use cases for Stencil include:

  • Creating design systems for large projects and organizations ( shareable UI components )

  • Creating portable parts of applications that can be shared and used in many different places. ( viewers, widgets, integrations, etc. )

You can find the GitHub repo for this project here.

This article has been originally written by Vlado Tesanovic at blog.logrocket

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

7 Best Javascript Iframe Libraries

7 Best Javascript Iframe Libraries

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

1. Zoid

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!
    It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!

Download


2. Postmate

Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort.

Download


3. Iframe Resizer

Keep same and cross domain iFrames sized to their content with support for window/content resizing, in page links, nesting and multiple iFrames

Demo

Download


4. Iframely

Embed proxy. Supports over 1800 domains via custom parsers, oEmbed, Twitter Cards and Open Graph

Demo

Download


5. React Frame component

This component allows you to encapsulate your entire React application or per component in an iFrame.

Demo

Download


6. Seamless.js

A seamless iframe makes it so that visitors are unable to distinguish between content within the iframe and content beside the iframe. Seamless.js is a JavaScript library (with no dependencies) that makes working with iframes easy by doing all the seamless stuff for you automatically.

Demo

Download


7. Porthole

A proxy to safely communicate to cross-domain iframes in javascript

Demo

Download


Thank for read!