Navigate back to the homepage

Immersive Functions

Ayush Chauhan
April 10th, 2020 · 4 min read

Immersive Reader is a tool that implements proven techniques to improve reading comprehension for emerging readers, language learners, and people with learning differences. The Immersive Reader is designed to make reading more accessible for everyone. The Immersive Reader

  • Shows content in a minimal reading view
  • Displays pictures of commonly used words
  • Highlights nouns, verbs, adjectives, and adverbs
  • Reads your content out loud to you
  • Translates your content into another language
  • Breaks down words into syllables

Azure Functions is a solution for easily running small pieces of code, or “functions,” in the cloud. It’s a serverless offering from Microsoft Azure.

Try the Demo here

Demo gif

In this blog post we will see how to enable Immersive reader for your frontend.

  • Learn how [Azure Functions](http://functions.azure.com/)  can access token from Azure portal on your web client’s behalf.
  • Add immersive reader to any website.
  • Enable images pls.
  • Working code sample is available here -

Tune in 🎶


Prerequisites 🥚 -

Go get your secrets first 🍕

  1. Go this page and Execute a powershell script

  2. Save the output as those are the secrets.

    0goGetYourSecrets.gif

    (Alt-text: Getting credentials for the project)

    It actually executes a powershell script which deploys immersive reader cognitive service, sets up azure active directory for your app and returns essential secrets.

Let’s Get Going 🍳

  1. Our first step will be installing Azure function core tools in local system so that we can test it. To do that we need to instruct npm to install and enable it for us.

1.gif

(Alt-text: Just open terminal and install azure function core tools.)

1npm install -g azure-functions-core-tools@3
  1. Initialise a function App. This will be a folder where azure functions will be created and stored.

    2CreateAzFuncProject.gif

    (Alt-text: Just open terminal and install azure function core tools.)

    Execute

    1func init APPNAME

    and choose node and JavaScript worker. You’ll see a folder generated with your APPNAME and consists host.json file. We will call this location as root of the directory.

  2. Let’s create a “HTTP Trigger” function now. This will be a serverless function endpoint which authenticates and passes us the token required to access immersive reader resource. “HTTP Trigger” here means the function to be triggered (Start execution) by HTTP requests.

    4.gif

    (Alt-text: Create a “HTTP Trigger” Azure function for our App)

    1func new --name GetTokenAndSubdomain --template "HTTP trigger"

    Meanwhile you will see a sub-folder generated after this execution with files index.js and function.json.

  3. Install Dependencies to be used in our app.

    Snag_1725cbc8.png

    (Alt-text: Installed axios dependency using npm)

    1npm i -s axios dotenv

    axios here is a js library that will help us with requesting the immersive service AD for token and dotenv will be used to load tokens and Secrets from .env file.

  4. Create .env file to add secrets that can be accessed by our function. We have to load our secrets which we obtained earlier by the powershell script.

    1TENANT_ID={YOUR_TENANT_ID}
    2CLIENT_ID={YOUR_CLIENT_ID}
    3CLIENT_SECRET={YOUR_CLIENT_SECRET}
    4SUBDOMAIN={YOUR_SUBDOMAIN}
  5. Copy the code below and paste it into index.js of our created function in step 3.

5.gif

(Alt-text: Paste the code below in Index.js of /GetTokenAndSubdomain function)

1require('dotenv').config();
2const axios = require('axios').default;
3
4module.exports = async function(context, req) {
5 try {
6 const tokenResponse = await axios.post(
7 `https://login.windows.net/${process.env.TENANT_ID}/oauth2/token`,
8 new URLSearchParams({
9 grant_type: 'client_credentials',
10 client_id: process.env.CLIENT_ID,
11 client_secret: process.env.CLIENT_SECRET,
12 resource: 'https://cognitiveservices.azure.com/'
13 }).toString(),
14 {
15 headers: {
16 'Content-Type': 'application/x-www-form-urlencoded'
17 }
18 }
19 );
20 var tokenResultParsed = tokenResponse.data;
21 context.res = {
22 status: 200,
23 body: { token: tokenResultParsed.access_token, subdomain: process.env.SUBDOMAIN }
24 };
25 } catch (err) {
26 console.log(err);
27 context.res = {
28 status: 500,
29 error: 'Unable to acquire Azure AD token. Check the debugger for more information.'
30 };
31 }
32};

This code is a simple Client Credentials OAuth2 handler for our function to grab token from Azure, It submits a post request to our Active Directory with our Client_ID and Client_Secret.

Line 1, Loads all the variables from .env file to actual processing environment. We are using them in our code with prefix process.env.

Line 6 starts the post request execution and it saves the data to tokenResponse . The token is extracted from the data JSON object using tokenResponse.data and stored into tokenResultParsed . context.res now returns the token to the frontend client or whoever hitting our endpoint.

You can go to root directory of the Function App and type

1func host start

which will start a local development server on port 7071.

Try accessing [localhost:7071/api/GetTokenAndSubdomain](http://localhost:7071/api/GetTokenAndSubdomain) in your browser and you’ll see a token render on page. If you do get a token, “Congrats! you’ve followed the blog correctly”. If not, Please go back and check for some points that you might have missed.

.
7. Let’s Deploy our Function app with VSCode and azure function extension. Moreover we also need to copy the azure function url with authorization code in order to have it accessed by client.

6.gif

(Alt-text: Deploy Azure function from VSCode and copy the function url in Azure portal)

8 . Now it’s time to embed Immersive reader js sdk in your HTML . Developing whole frontend is again out of the scope for this blog, however I’ll describe how to get your sample html up and running. Grab the sample HTML site from here.

line no. 10. loads the immersive reader Javascript sdk

1<script
2 src="https://contentstorage.onenote.office.net/onenoteltir/immersivereadersdk/immersive-reader-sdk.1.0.0.js">
3</script>

line 25 has a button with class immersive-reader-button Which on click handles function on line 75. handleLaunchImmersiveReader() Handles the authentication by executing the function getTokenAndSubdomainAsync() on line 55.

getTokenAndSubdomainAsync() sends a get request to our function with url on line 58. we need to paste URL obtained in step 7 here so that our client can access it. line 82 and 83 extracts token and subdomain which is passed in ImmersiveReader.launchAsync() .

line 87 has the extracts title from #ir-title class used in 26, Similarly content data which also needs to be passed in ImmersiveReader.launchAsync() is passed from #ir-content html class on line 27. Notice how the lang="en-us" is used to specify the language and dir="rtl"is used to specify rtl languages.

ImmersiveReader.launchAsync() Launches a iframe with beautiful immersive reader. You can deploy the sample anywhere you like, ex. GitHub pages (in a private repo) or zeit.co learn how to deploy site in 15s with zeit here.

Point 🎯: The GetTokenAndSubdomain API endpoint should be secured behind some form of authentication (for example, OAuth) to prevent unauthorized users from obtaining tokens to use against your Immersive Reader service and billing; that work is beyond the scope of this quickstart.

You can access the JS SDK Refrence here.

9 . Oops, we have a problem after deployment of frontend. Probably that’s a CORS issue.

cors.jpg

(Alt-text:Cross Origin Resource sharing issue)

This is why the frontend can’t access our function because Azure has some security enabled by default. Cross Origin Resource Sharing is a technique that permits resource sharing between scripts running on a browser client and resources from a different origin.

Let’s disable CORS just for our frontend so that it can have access to our function.

7.gif

(Alt-text: Solving Cross Origin Resource sharing issue from Azure portal)

10 . Stay at Home


Thanks for reading

Let me know the feedback. Follow / Subscribe for more awesome azure content.

Join our email list and get notified about new content

Be the first to receive our latest content with the ability to opt-out at anytime. We promise to not spam your inbox or share your email with any third parties.

More articles from Blogs and Stories by heyAyush

Deploy your frontend in 15 seconds with Zeit Now

When I started deploying my frontends and stactic sites on zeit, I've never looked back. Zeit offers fast and zero config deployments and is…

April 9th, 2020 · 1 min read

Introducing Sync Routine Framework

Introducing Sync Routine Framework Sync Routine framework is to create awareness of your well being and not to lose your sh t in the giant…

April 3rd, 2020 · 2 min read
© 2018–2021 Blogs and Stories by heyAyush
Link to $https://twitter.com/heyayushhLink to $https://github.com/heyayushhLink to $https://instagram.com/heyayushhLink to $https://www.linkedin.com/in/heyayushh/