logo
Loading...

All Articles

thumbnail

1/30/2024, 10:08:23 PM

Browser Compatability

Web developers will often have a preferred Internet browser. Naturally, that same browser is the one used to preview websites and web applications in development. There are, however, a multitude of browsers (and many versions of those browsers), resulting in a variety of experiences for users. This creates a problem for developers: how can we ensure that a website is compatible across as many browsers as possible? In this article, you’ll learn about the varying, default CSS rules that different browsers apply to HTML, how to reset default browser CSS, and how to increase browser compatibility for websites. Or if you prefer a more hands-on approach, try our Learn CSS and Learn Intermediate CSS courses. User Agent Style Sheets When building a website, you’ve probably noticed that heading elements like h1 are always a default size (and font) or that hyperlinks always appear blue and underlined, all before you add your own styles. Why is that so? And how does that happen? All browsers have a default set of CSS rules that they apply to HTML. The default CSS rules live in a stylesheet specific to the browser. The stylesheet is known as a user agent style sheet. If you were to view the same website across many different web browsers, you might notice that the website looks different in each browser. This is because each browser has its own user agent stylesheet. This variance in user agent style sheets is what makes it difficult to create a website that is consistent across all browsers. Resetting User Agent Stylesheets Designing a website across browsers with different user agent stylesheets can be a frustrating experience. To avoid this problem, it’s very common to reset the user agent stylesheets using a CSS reset stylesheet (often shortened to “CSS reset”). CSS resets remove all browser-added styling to make sure that all content starts at the same starting point for developers. Using a CSS reset stylesheet can be accomplished using the following steps: Create a reset.css file. Copy and paste CSS reset rules into the reset.css file. Link to reset.css in the HTML file (make sure reset.css is loaded first before other CSS files, otherwise reset.css may reset your custom rules by accident). <!DOCTYPE html> <html> <head> <title>My Title</title> <link href="reset.css" type="text/css" rel="stylesheet"> <link href="styles.css" type="text/css" rel="stylesheet"> </head> The example above demonstrates a reset.css stylesheet linked in an HTML file. A popular CSS reset can be found here. Browser Support When new browsers are developed (or an existing browser is updated), they often include new features that weren’t previously available. The result, however, is a multitude of browsers with varying functionalities. To avoid inconsistencies across browsers when creating a website, developers must ensure that newer HTML or CSS features are supported in each browser. The following resource is an up-to-date record of CSS properties across many versions of many browsers: “Can I use“ For example, if you search “Can I use” for the CSS property filter (a property that can add a visual effect to an image), you’ll see that it is supported in most browsers, except for Internet Explorer 11 and Opera Mini. When a feature is searched using the resource above, the search results include a support matrix. The support matrix outlines which browsers (and browser versions) support the feature. The bottom of the pane also includes information about known issues and bugs. Global Support vs Unprefixed Support In the top-right corner of “Can I use”, there is information on “global support” and “unprefixed support”. What do these terms mean and what is the difference between them? As stated earlier, every browser has its own implementation of many newer CSS rules. To distinguish their own implementation, browsers add a prefix to the CSS property. The prefix is known as a vendor prefix. For example, the -moz vendor prefix refers to Mozilla Firefox’s implementation. A full list of vendor prefixes can be found here. The following code demonstrates how the transition property is implemented across all browsers using vendor prefixes. h1 { -webkit-transition: all 4s ease; -moz-transition: all 4s ease; -ms-transition: all 4s ease; -o-transition: all 4s ease; transition: all 4s ease; } The “global support” value mentioned earlier represents the percentage of supported browsers for the specified feature if all necessary prefixes are used (as is the case in the previous example). The “unprefixed support” value represents the percentage of supported browsers for the feature if no prefixes are used (if just the transition declaration were written in the previous example). To identify exactly which CSS properties need vendor prefixes, you can use tools like this one to generate all of the necessary vendor prefixes for you. Polyfills Even with vendor prefixes, what if a user is using a browser that doesn’t support newer browser functionalities? Developers have created libraries called polyfills to support such users. Polyfills: Detect the user’s browser. Collect information about which features are supported by the browser. Return the collected information to your website. The collected information allows you to write alternative CSS for browsers that are missing certain features. Your website may not look as visually appealing as it would on a newer browser, but it will function. One example of a polyfill is Modernizr. To use Modernizr: Navigate to the website and click “Download.” Click the + next to any features you want to polyfill. Click “Build.” Click “Download” next to the “Build” option in the resulting pop-up. This will prompt you to download a JavaScript file (the polyfill code). Place the downloaded .js file (JavaScript file) into the corresponding folder in your website’s directory. Link the JavaScript file using a <source> tag in your index.html file. Use CSS to target elements that have the detected feature using .feature-name. To target elements that don’t have the detected feature use .no-feature-name. The code feature-name is intended to represent the actual CSS feature. An example of alternative CSS rules from the Modernizr documentation: /* Use this rule if the user's browser doesn't support gradients */ .no-cssgradients .header { background: url("images/glossybutton.png"); } /* Use this rule if the user's browser does support gradients */ .cssgradients .header { background-image: linear-gradient(cornflowerblue, rebeccapurple); } Review Let’s review what you’ve learned about browser compatibility. A website may not look the same in all browsers (or versions of browsers) due to differing user agent stylesheets across browsers. User agent stylesheets can be reset with a CSS reset stylesheet. A CSS reset stylesheet can be linked in an HTML file. Resources like “Can I use” allow you to check if a CSS feature is supported across multiple browsers. Vendor prefixes increase the browser compatibility of CSS features. This is because they indicate to browsers how the rule should be specifically implemented. Polyfills are libraries that increase the browser compatibility of a website. They allow developers to write alternative CSS rules based on whether or not a browser supports a certain feature. Users have the option of selecting from a multitude of browsers and browser versions. Because of this, it’s important to create websites that are compatible across a wide array of browsers. Increasing your website’s browser compatibility is not only good practice, it also increases your website’s accessibility to the potential billions of users around the globe.

Click to read more!

thumbnail

1/30/2024, 10:11:44 PM

Authentication and OAuth

Introduction Authentication is the process used by applications to determine and confirm identities of users. It ensures that the correct content is shown to users. More importantly, it ensures that incorrect content is secured and unavailable to unauthorized users. In this article, we’ll discuss a few of the common design patterns for these interactions. You’ll need to have some basic understanding of HTTP requests, since these methods all use HTTP requests to exchange information. Password Authentication The most common implementation of authentication requires a user to input their username or email and a password. The application’s server then checks the supplied credentials to determine if the user exists and if the supplied password is correct. If the credentials are correct, the user is logged in and able to use the application as that user. Typically, upon a successful login, the application will respond with an authentication token (or auth token) for the client to use for additional HTTP requests. This token is then stored on the user’s computer, preventing the need for users to continuously log in. This token generally expires after a certain amount of time, ensuring the correct user is using the application over time as well. API Keys While it is common to think of authentication as the interaction between a human user and an application, sometimes the user is another application. Many apps expose interfaces to their information in the form of an API (application program interface). For example, the Spotify API provides endpoints for almost all of its functionality. This allows applications to fetch data from the Spotify music catalog and manage user’s playlists and saved music. Since these external requests could overwhelm a service and also access user information, they need to be secured using authentication. The most basic pattern for API access from another application is using an API key. Public APIs usually provide a developer portal where you can register your application and generate a corresponding API key. This key is then unique to your application. When your application makes a request, this key is sent along with it. The API can then verify that your application is allowed access and provide the correct response based on the permission level of your application. The API can track what type and frequency of requests each application is making. This data can be used to throttle requests from a specific application to a pre-defined level of service. This prevents applications from spamming an endpoint or abusing user data, since the API can easily block that application’s API key and prevent further malicious use of the API by that application. OAuth For many applications, a generic developer-level API key is not sufficient. As mentioned earlier, APIs sometimes have the ability to provide access to user-level data. However, most services only provide this private data if the user enables it. For example, Facebook doesn’t want Tinder to access all of their users’ data, just the users who have opted in to allowing the sharing of data to better help them find a match in their area. A basic approach to this problem might be to have the user provide their login credentials to the intermediary application, but this is not very secure and would give full access to the requesting application, when the requesting application might only need a very limited set of privileges to function. OAuth defines a more elegant approach to this problem. It was developed in November 2006 by lead Twitter developer Blaine Cook and version 1.0 was published in April 2010. OAuth is an open standard and is commonly used to grant permission for applications to access user information without forcing users to give away their passwords. An open standard is a publicly available definition of how some functionality should work. However, the standard does not actually build out that functionality. As a result, each API is required to implement their own version of OAuth and therefore may have a slightly different implementation or flow. However, they’re all based around the same OAuth specification. This can make using a new OAuth API a little more frustrating. However, with time you will begin noticing the similarities between API authentication flows and be able to use them in your applications with increasing ease. Below is a summary of the standard OAuth flow. Generic OAuth Flow Many applications implementing OAuth will first ask the user to select which service they would like to use for credentials: authenticationLogin After selecting the service, the user will be redirected to the service to login. This login confirms the user’s identity and typically provides the user with a list of permissions the originating application is attempting to gain on the user’s account. If the user confirms they want to allow this access, they will be redirected back to the original site, along with an access token. This access token is then saved by the originating application. Like a developer API key, this access token will be included on requests by the application to prove that the user has granted access and enable access to the appropriate content for that user. When a user returns to the application, the token will be retrieved and they will not have to re-authenticate. OAuth 2 Since OAuth evolved out of Twitter, there were important use cases not originally considered as part of the specification. Eventually, this led to the creation of a new version of the specification, called OAuth 2. Among other improvements, OAuth 2 allows for different authentication flows depending on the specific application requesting access and the level of access being requested. OAuth 2 is still an open standard, so each API will have its own flow based on its particular implementation. Below, we’ll discuss a few of the common OAuth 2 flows and how they are used. Client Credentials Grant Sometimes an application will not need access to user information but may implement the added security and consistency of the OAuth 2 specification. This type of grant is used to access application-level data (similar to the developer API key above) and the end user does not participate in this flow. Instead of an API key, a client ID and a client secret (strings provided to the application when it was authorized to use the API) are exchanged for an access token (and sometimes a refresh token). We will discuss refresh tokens in more depth later. This flow is similar to our first example, where an email and password were exchanged for an authentication token. It is essential to ensure the client secret does not become public information, just like a password. As a result, developers should be careful not to accidentally commit this information to a public git repository. Additionally, to ensure integrity of the secret key, it should not be exposed on the client-side and all requests containing it should be sent server-side. Similar to the previously-mentioned keys, the returned access token is included on requests to identify the client making the requests and is subject to API restrictions. This access token is often short-lived, expiring frequently. Upon expiration, a new access token can be obtained by re-sending the client credentials or, preferably, a refresh token. Refresh tokens are an important feature of the OAuth 2 updates, encouraging access tokens to expire often and, as a result, be continuously changed (in the original OAuth specification, access tokens could last for time periods in the range of years). When a refresh token is used to generate a new access token, it typically expires any previous access tokens. Authorization Code Grant This flow is one of the most common implementations of OAuth and will look familiar if you’ve ever signed into a web application with Google or Facebook. It is similar to the OAuth flow described earlier with an added step linking the requesting application to the authentication. A user is redirected to the authenticating site, verifies the application requesting access and permissions, and is redirected back to the referring site with an authorization code. The requesting application then takes this code and submits it to the authenticating API, along with the application’s client ID and client secret to receive an access token and a refresh token. This access token and refresh token are then used in the same manner as the previous flow. To avoid exposing the client ID and secret, this step of the flow should be done on the server side of the requesting application. Since tokens are tied both to users and requesting applications, the API has a great deal of control over limiting access based on user behavior, application behavior, or both. Implicit Grant The previous two methods cause the client secret key to be exposed, so they need to be handled server-side. Some applications may need to access an OAuth API but don’t have the necessary server-side capabilities to keep this information secure. The Implicit Grant OAuth flow was designed for this very use case. This flow prompts the user through similar authorization steps as the Authorization Code flow, but does not involve the exchange of the client secret. The result of this interaction is an access token, and typically no refresh token. The access token is then used by application to make additional requests to the service, but is not sent to the server side of the requesting application. This flow allows applications to use OAuth APIs without fear of potentially exposing long-term access to a user or application’s information. Conclusion OAuth provides powerful access to a diverse set of sites and information. By using it correctly, you can reduce sign-up friction and enrich user experience in your applications.

Click to read more!

thumbnail

1/30/2024, 10:13:52 PM

Deploying to Github Pages

GitHub is a great tool to store projects and to collaborate with others, but its usefulness does not stop there. We’ll use a service called GitHub Pages to share our web page creations on the World Wide Web. What is GitHub Pages? There are many different ways to deploy a website to the public Internet. We’ll be using GitHub’s free service called GitHub Pages. Why GitHub Pages? GitHub Pages offers a lot of features and flexibility, all for free. Some of the benefits include: Easy setup Seamless collaboration using Git and GitHub Free hosting with >95% uptime Live updating with normal GitHub workflow What is Deploying? Deploying is like publishing. When authors are ready for their work to be seen by the world, they publish it. When web developers are ready to share their projects, they deploy to the World Wide Web. Deployment is when a project is packaged and shared on the Internet. Unlike publishing, however, deployment may occur many, many times over the course of a software project. Deployment on GitHub Pages Deploying to GitHub Pages is automatic. Once it’s set up, deploying happens whenever you push your local changes to your remote, GitHub-hosted repository. Head to GitHub Pages’ setup instructions and follow the steps exactly to get your main GitHub Pages page setup. When you first navigate to your newly deployed site it is possible that you will receive a 404 error. If this happens, and you are confident that you have followed all the steps as written, check back in 30 minutes to see if the deploy has successfully gone through. Viewing Your Live Web Page That’s it! Your website is deployed to the Internet! You and anyone with whom you share this link can view your project by navigating in your browser to the URL http://<your-github-username>.github.io. Adding GitHub Pages Projects You can set up your GitHub Pages to deploy every one of your repositories in addition to <username>.github.io. This will allow you to ensure all of your sites are deployed automatically whenever you push to GitHub. In GitHub, navigate to your <username>.github.io repository and click Settings. githubSettings Within Settings, navigate to the Source section within the Github Pages section. From the dropdown menu, select master branch and then click Save. githubPagesSection Now, all of your repositories can be found at http://<username>.github.io/<repository-name>. Try creating a new repo with an HTML project inside it (perhaps push an old project to GitHub) and then navigate to the deployed page. Deploying New Changes Now that your GitHub Pages site is set up, deploying new changes is easy. Every time you make a change to your site, use the normal GitHub flow. That is, use git commit and git push to send your changes to GitHub. After this, the GitHub site should update within a few seconds. Just refresh the page in your browser, and you’re good to go! Congratulations on your first live web page!

Click to read more!

thumbnail

1/31/2024, 2:43:22 AM

Getting User Input in Node.js

Learn how to handle user input synchronously in Node.js. Synchronous Input Node.js allows you to run JavaScript code outside of a browser window, offering powerful tools to interact with a computer filesystem, run web servers, and create terminal applications. Node handles these tasks by running asynchronously, which means that reading user input from a terminal isn’t as simple as calling a getInput() function. In this article, we’ll show you an easy way around that (and some tips and tricks for handling user input) by using a helpful Node module. Working with Input Node.js provides a few ways to handle interactions, including the built-in process object and readline module. While these are powerful tools, they rely on callback functions and can be confusing to work with at first. const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.question('Who are you?', name => { console.log(`Hey there ${name}!`); readline.close(); }); Running this code in Node, you’d see: $ node read.js Who are you? > Then you could enter your input based on the prompt and see the response: $ node read.js Who are you? > Codecademy Hey there Codecademy! $ This works as intended, but it’s a lot of boilerplate, and you need to call readline.question() and create a callback function every time you want to use it for input. There’s a simpler way, whether you’re just getting started out with JavaScript development or just want to get an interactive script running as quickly as possible. Using prompt-sync The prompt-sync Node module provides an easy-to-use alternative to this callback-based syntax. Make sure you have Node and NPM installed Run npm install prompt-sync in the terminal const prompt = require('prompt-sync')(); Notice the extra () after require(). The prompt-sync module is a function that creates prompting functions, so you need to call prompt-sync in order to get your actual prompting function. Once you’ve loaded the prompt-sync module and called it, using it to retrieve user input is relatively straightforward: const prompt = require('prompt-sync')(); const name = prompt('What is your name?'); console.log(`Hey there ${name}`); The prompt() function returns the user feedback, so simply store that return value to a variable to use it later. In the example above, the name variable stores the value, and it is then repeated to the user on the next line. Letting Users Exit By default, most terminal programs will exit with Ctrl + C (This sends a SIGINT, or “signal interrupt” message indicating that a user wants to exit a program). With prompt-sync, in order to make sure that your users can exit at will, add a configuration object with sigint: true when invoking the prompt-sync function: const prompt = require('prompt-sync')({sigint: true}); Working with Numbers All user input will be read as a String, so in order to treat user input as numbers, you’ll need to convert the input: const num = prompt('Enter a number: '); console.log('Your number + 4 ='); console.log(Number(num) + 4); Making a basic app The code below creates a small number guessing application. const prompt = require('prompt-sync')({sigint: true}); // Random number from 1 - 10 const numberToGuess = Math.floor(Math.random() * 10) + 1; // This variable is used to determine if the app should continue prompting the user for input let foundCorrectNumber = false; while (!foundCorrectNumber) { // Get user input let guess = prompt('Guess a number from 1 to 10: '); // Convert the string input to a number guess = Number(guess); // Compare the guess to the secret answer and let the user know. if (guess === numberToGuess) { console.log('Congrats, you got it!'); foundCorrectNumber = true; } else { console.log('Sorry, guess again!'); } }

Click to read more!

thumbnail

1/31/2024, 3:21:42 AM

HTTP Errors: 404

An introduction to the Web's most popular error Background: There are five types of HTTP status codes that report on communications between the client and server. The 400-level codes denote a client-side error, meaning an error that originated from an action taken by the user of a web app. Sometimes you’ll see a 404 error if you incorrectly type the URL to a web page you want to visit, and instead of being taken there, you’re rerouted to a page that reads something like, “404 Error - File Not Found.” The 404 error is telling you that the request you sent did in fact make it to the server, but the server could not find the specific file you were requesting. Other actions that will set off a 404 error: Clicking a link to a file that has been deleted or renamed Using Your Browser’s Developer Tools to Check Status Codes: Many modern browsers have a “developer tools” mode that allows you to access loads of meta-data about web pages. Here’s how to use Google Chrome’s Developer Tools to check the status codes of files on the web. (Other browsers’ developer tools have this feature too, but you’ll have to google those to learn more.) Instructions: If on a Mac, go to a web page of your choosing and press down the control button while you click anywhere on the document. If you’re on a PC, just right-click anywhere in the document. A menu will pop up next to where you clicked. Click the “Inspect Element” option. The developer tools panel will show up in the bottom third of your screen. Don’t be afraid! It will go away if you click the small “x” at the top far-right of the panel. To check status codes of the files listed on the web page, click on the “Network” tab (the second tab from the right, directly after “Elements”). On the bottom half of the panel for this tab, you’ll see a table listing information about all the files associated with that web page. The “Status” column will show you the HTTP status of each file. Do some exploring! Click buttons and links on the web page you’ve visited, and see what changes in the “Network” tab. If you see a status code written in red, it means there was an error. Maybe it’s a 404. Check it out!

Click to read more!

Leo's Blog
© 2024 Leo's Blog
github linklinkedin link