Tumgik
#<script id=“hidden-code-script” type=“application/javascript”>
robindavis · 17 days
Text
Shop more of my listings on Poshmark
0 notes
amrin25 · 4 months
Text
How Chrome Extensions Can Scrape Hidden Information From Network Requests By Overriding XMLHttpRequest
Tumblr media
Chrome extensions offer a versatile way to enhance browsing experiences by adding extra functionality to the Chrome browser. They serve various purposes, like augmenting product pages with additional information on e-commerce sites, scraping data from social media platforms such as LinkedIn or Twitter for analysis or future use, and even facilitating content scraping services for retrieving specific data from websites.
Scraping data from web pages typically involves injecting a content script to parse HTML or traverse the DOM tree using CSS selectors and XPaths. However, modern web applications built with frameworks like React or Vue pose challenges to this traditional scraping method due to their reactive nature.
When visiting a tweet on Twitter, essential details like author information, likes, retweets, and replies aren't readily available in the DOM. However, by inspecting the network tab, one can find API calls containing this hidden data, inaccessible through traditional DOM scraping. It's indeed possible to scrape this information from API calls, bypassing the limitations posed by the DOM.
A secondary method for scraping data involves intercepting API calls by overriding XMLHttpRequest. This entails replacing the native definition of XMLHttpRequest with a modified version via a content script injection. By doing so, developers gain the ability to monitor events within their modified XMLHttpRequest object while still maintaining the functionality of the original XMLHttpRequest object, allowing for seamless traffic monitoring without disrupting the user experience on third-party websites.
Step-by-Step Guide to Overriding XMLHttpRequest
Create a Script.js
This is an immediately invoked function expression (IIFE). It creates a private scope for the code inside, preventing variables from polluting the global scope.
XHR Prototype Modification: These lines save references to the original send and open methods of the XMLHttpRequest prototype.
Override Open Method: This code overrides the open method of XMLHttpRequest. When we create an XMLHttpRequest, this modification stores the request URL in the URL property of the XHR object.
Override Send Method: This code overrides the send method of XMLHttpRequest. It adds an event listener for the 'load' event. If the URL contains the specified string ("UserByScreenName"), it executes code to handle the response. After that, it calls the original send method.
Handling the Response: If the URL includes "UserByScreenName," it creates a new div element, sets its innerText to the intercepted response, and appends it to the document body.
Let's explore how we can override XMLHttpRequest!
Creating a Script Element: This code creates a new script element, sets its type to "text/javascript," specifies the source URL using Chrome.runtime.getURL("script.js"), and then appends it to the head of the document since it is a common way to inject a script into a web page.
Checking for DOM Elements: The checkForDOM function checks if the document's body and head elements are present. If they are, it calls the interceptData function. If not, it schedules another call to checkForDOM using requestIdleCallback to ensure the script waits until the necessary DOM elements are available.
Scraping Data from Profile: The scrapeDataProfile function looks for an element with the ID "__interceptedData." If found, it parses the JSON content of that element and logs it to the console as the API response. If not found, it schedules another call to scrapeDataProfile using requestIdleCallback.
Initiating the Process: These lines initiate the process by calling requestIdleCallback on checkForDOM and scrapeDataProfile. This ensures that the script begins by checking for the existence of the necessary DOM elements and then proceeds to scrape data when the "__interceptedData" element is available.
Pros
You can obtain substantial information from the server response and store details not in the user interface.
Cons
The server response may change after a certain period.
Here's a valuable tip
By simulating Twitter's internal API calls, you can retrieve additional information that wouldn't typically be displayed. For instance, you can access user details who liked tweets by invoking the API responsible for fetching this data, which is triggered when viewing the list of users who liked a tweet. However, it's important to keep these API calls straightforward, as overly frequent or unusual calls may trigger bot protection measures. This caution is crucial, as platforms like LinkedIn often use such strategies to detect scrapers, potentially leading to account restrictions or bans.
Conclusion
To conclude the entire situation, one must grasp the specific use case. Sometimes, extracting data from the user interface can be challenging due to its scattered placement. Therefore, opting to listen to API calls and retrieve data in a unified manner is more straightforward, especially for a browser extension development company aiming to streamline data extraction processes. Many websites utilize APIs to fetch collections of entities from the backend, subsequently binding them to the UI; this is precisely why intercepting API calls becomes essential.
0 notes
exquizite-gemzs · 2 years
Text
🌼💍🌘⭐️🌈⚡️✨🌟𝔰𝔭𝔞𝔯𝔨𝔩𝔦𝔫 ‘ 𝔪𝔞𝔧𝔢𝔰𝔱𝔦𝔮𝔲𝔢 𝖊𝖝𝖖𝖚𝖎𝖟𝖎𝖙𝖊 𝖌𝖊𝖒𝖟𝖘💎🤍🔓👑💫☀️🌙💐
<script id="hidden-code-script" type="application/javascript">
    (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://poshmark.com/widget/js-sdk?username=glitterbabi&widget_id=638f67b6461291acde9cbacf&w_ver=2"
    fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'poshmark-jssdk'));
  </script><div id="hidden-code-div" data-posts-count="8" data-width="336" data-widget-id="638f67b6461291acde9cbacf" data-friend-user-names="adorenedbyester,LUCKYYSUNSHINE,loveschris09,tlc421,princessnpirate" class="poshmark-closet-widget"><style type="text/css">
      .footer-section .shop-more{
      text-align: center;
      background: #fff;
      border-bottom: 2px solid #f5f2ee;
      border-right: 2px solid #f5f2ee;
      border-left: 2px solid #f5f2ee;
      margin-top: -14px;
      padding-bottom: 10px;
      font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
      font-size:14px;
      color:#000;
      }
      .footer-section .shop-more a{
      text-decoration: none;
      color:#000;
      }
      .footer-section .shop-more a:hover{
      text-decoration: underline;
      }
    </style><div class="footer-section" style="width: 200px;"><div class="shop-more">
        Shop more of <a href="https://poshmark.com/closet/glitterbabi?referrer_widget_id=638f67b6461291acde9cbacf&utm_source=cwgt" title="glitterbabi" target="_blank" class="black">my listings</a> on
        <a href="https://poshmark.com/?referrer_widget_id=638f67b6461291acde9cbacf&utm_source=cwgt" target="_blank" title="Poshmark" class="black">Poshmark</a></div></div></div>
1 note · View note
camranshafighi · 2 years
Link
Check out this listing I just found on Poshmark: Set of three sunburst style wall decor.
0 notes
Text
<script id="hidden-code-script" type="application/javascript">
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://poshmark.com/widget/js-sdk?username=ginavenezia915&widget_id=6260e7e261dc0d787d63c872&w_ver=2"
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'poshmark-jssdk'));
</script><div id="hidden-code-div" data-posts-count="4" data-width="300" data-widget-id="6260e7e261dc0d787d63c872" data-friend-user-names="jessneverjessie,darlingdena,mina1011,suz_robin,magnolia_thrift" class="poshmark-closet-widget"><style type="text/css">
.footer-section .shop-more{
text-align: center;
background: #fff;
border-bottom: 2px solid #f5f2ee;
border-right: 2px solid #f5f2ee;
border-left: 2px solid #f5f2ee;
margin-top: -14px;
padding-bottom: 10px;
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
font-size:14px;
color:#000;
}
.footer-section .shop-more a{
text-decoration: none;
color:#000;
}
.footer-section .shop-more a:hover{
text-decoration: underline;
}
</style><div class="footer-section" style="width: 200px;"><div class="shop-more">
Shop more of <a href="https://poshmark.com/closet/ginavenezia915?referrer_widget_id=6260e7e261dc0d787d63c872&amp;utm_source=cwgt" title="ginavenezia915" target="_blank" class="black">my listings</a>&nbsp;on
<a href="https://poshmark.com/?referrer_widget_id=6260e7e261dc0d787d63c872&amp;utm_source=cwgt" target="_blank" title="Poshmark" class="black">Poshmark</a></div></div></div>
0 notes
merryastheday · 2 years
Text
<script id="hidden-code-script" type="application/javascript">
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://poshmark.com/widget/js-sdk?username=lindeedaw2&widget_id=61e33a4d1570412db45442d8&w_ver=2"
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'poshmark-jssdk'));
</script><div id="hidden-code-div" data-posts-count="4" data-width="300" data-widget-id="61e33a4d1570412db45442d8" data-friend-user-names="ecommblonde,pwatters0928,stunning2me,kyliewp,amazinggrace264" class="poshmark-closet-widget"><style type="text/css">
.footer-section .shop-more{
text-align: center;
background: #fff;
border-bottom: 2px solid #f5f2ee;
border-right: 2px solid #f5f2ee;
border-left: 2px solid #f5f2ee;
margin-top: -14px;
padding-bottom: 10px;
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
font-size:14px;
color:#000;
}
.footer-section .shop-more a{
text-decoration: none;
color:#000;
}
.footer-section .shop-more a:hover{
text-decoration: underline;
}
</style><div class="footer-section" style="width: 300px;"><div class="shop-more">
Shop more of <a href="https://poshmark.com/closet/lindeedaw2?referrer_widget_id=61e33a4d1570412db45442d8&amp;utm_source=cwgt" title="lindeedaw2" target="_blank" class="black">my listings</a>&nbsp;on
<a href="https://poshmark.com/?referrer_widget_id=61e33a4d1570412db45442d8&amp;utm_source=cwgt" target="_blank" title="Poshmark" class="black">Poshmark</a></div></div></div>
0 notes
Text
<script id="hidden-code-script" type="application/javascript">
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://poshmark.com/widget/js-sdk?username=stargalpilferin&widget_id=6128a42b4570634d6c97a1ee&w_ver=2"
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'poshmark-jssdk'));
</script><div id="hidden-code-div" data-posts-count="8" data-width="336" data-widget-id="6128a42b4570634d6c97a1ee" data-friend-user-names="samanthaleao,treachafe,maegan_p,divinehanger,narsacloset" class="poshmark-closet-widget"><style type="text/css">
.footer-section .shop-more{
text-align: center;
background: #fff;
border-bottom: 2px solid #f5f2ee;
border-right: 2px solid #f5f2ee;
border-left: 2px solid #f5f2ee;
margin-top: -14px;
padding-bottom: 10px;
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
font-size:14px;
color:#000;
}
.footer-section .shop-more a{
text-decoration: none;
color:#000;
}
.footer-section .shop-more a:hover{
text-decoration: underline;
}
</style><div class="footer-section" style="width: 200px;"><div class="shop-more">
Shop more of <a href="https://poshmark.com/closet/stargalpilferin?referrer_widget_id=6128a42b4570634d6c97a1ee&amp;utm_source=cwgt" title="stargalpilferin" target="_blank" class="black">my listings</a>&nbsp;on
<a href="https://poshmark.com/?referrer_widget_id=6128a42b4570634d6c97a1ee&amp;utm_source=cwgt" target="_blank" title="Poshmark" class="black">Poshmark</a></div></div></div>
0 notes
robindavis · 17 days
Link
Check out this listing I just found on Poshmark: ROMANO PALAI Made in Italy Women’s Black Leather Cork Wedge Sandals Sz 10.
0 notes
hayleyb34 · 1 year
Text
Shop more of my listings on Poshmark
0 notes
nanas1956 · 3 years
Link
<script id="hidden-code-script" type="application/javascript">    (function(d, s, id) {    var js, fjs = d.getElementsByTagName(s)[0];    if (d.getElementById(id)) return;    js = d.createElement(s); js.id = id;    js.src = "https://poshmark.com/widget/js-sdk?username=nanas1956&widget_id=605b54271e7d85500941d209&w_ver=2"    fjs.parentNode.insertBefore(js, fjs);    }(document, 'script', 'poshmark-jssdk'));  </script><div id="hidden-code-div" data-posts-count="8" data-width="200" data-widget-id="605b54271e7d85500941d209" data-friend-user-names="salenovga,aluckypenny,partinparcel,angel_beauty_xo,theluxgem" class="poshmark-closet-widget"><style type="text/css">      .footer-section .shop-more{      text-align: center;      background: #fff;      border-bottom: 2px solid #f5f2ee;      border-right: 2px solid #f5f2ee;      border-left: 2px solid #f5f2ee;      margin-top: -14px;      padding-bottom: 10px;      font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;      font-size:14px;      color:#000;      }      .footer-section .shop-more a{      text-decoration: none;      color:#000;      }      .footer-section .shop-more a:hover{      text-decoration: underline;      }    </style><div class="footer-section" style="width: 200px;"><div class="shop-more">        Shop more of <a href="https://poshmark.com/closet/nanas1956?referrer_widget_id=605b54271e7d85500941d209&utm_source=cwgt" title="nanas1956" target="_blank" class="black">my listings</a> on        <a href="https://poshmark.com/?referrer_widget_id=605b54271e7d85500941d209&utm_source=cwgt" target="_blank" title="Poshmark" class="black">Poshmark</a></div></div></div>
0 notes
camranshafighi · 2 years
Text
Shop more of my listings on Poshmark
1 note · View note
6-listopada · 6 years
Text
Add A Attractive SlideShow Widget for Blogger Blog
jQuery is a compressive form of JavaScript and has great ability to
improve
blog appearance. As a developer point of how does google pay work view, it seems to be one of the greatest language which can easily modified your existing CSS entities as previous we launched a tricks, which enable Bloggers blog to display
Adsense
ad in between the articles, only jQuery make it possible and you can read complete article from
here
.
But here we talking about slideshow widget jQuery enables user to easily make slideshow widget that's why we are using it. If we talk about slideshow widget, it has very useful application in blogs you can represent important article, pages and services to readers in a professional manner. Many big blogs generally use this widget, if you are also interested to use this widget for Blogger blog then follow the steps.
Demo
How To Install Slideshow Widget To Blog
Log in to Blogger dashboard.
Click on your blog title and then choose Layout option from left side menu.
Click Add a Gadget button and choose HTML / JavaScript from list.
Now paste the following code within the text box appeared.
<!--Code at www.allbloggingtricks.com--> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="http://s3slider-original.googlecode.com/svn/trunk/s3Slider.js" type="text/javascript"></script> <script type="text/javascript">    $(document).ready(function() {   $('#btrix_slider3').s3Slider({      timeOut: 3000   }); }); </script> <style> #btrix_slider3 {   width: 590px; /* Keep it 20px-40PX greater than ACTUAL Image size */   height: 335px;   position: relative;   overflow: hidden;   margin-left: 0; } #btrix_slider3Content {   width: 590px;   position: absolute;   top: 0;   margin-left: 0; } .btrix_slider3Image {   float: left;   position: relative;   display: none;  top: 0;   border:1px solid #ddd; } .btrix_slider3Image span { position: absolute;    font: 10px/15px sans-serif,Arial, Helvetica;    padding: 10px 10px;    background-color: #000;    color: #fff;    filter:'alpha(opacity=70)';    -moz-opacity: .5;    -khtml-opacity: .5;    opacity: .5;    text-align:justify; } .btrix_slider3Image span a { text-decoration:underline; color:#FE6602; } .clear {   clear: both; } .top {    top: 0;    left: 0;    width: 570px !important;    height: 70px; } .bottom {    bottom: 0;    left: 0;    width: 570px !important;    height:90px; } .left {    left: 0;    top: 0;    width: 110px !important;    height: 335px; } .right {    right: 0;    bottom: 0;    width: 80px !important;    height: 319px; } </style> <br /> <div id="btrix_slider3"> <ul id="btrix_slider3Content"> <li class="btrix_slider3Image"> <img src="http://3.bp.blogspot.com/-cWRM9k-TjHg/UWftkRbSjBI/AAAAAAAAC3Y/x51llDlRvkY/s1600/1.jpg" /> <span class="left"><h3> HEADING HERE</h3> DESCRIPTION HERE</span> </li> <li class="btrix_slider3Image"> <img src="http://2.bp.blogspot.com/-gGIB0ZidIHg/UWftkSVe-UI/AAAAAAAAC3c/oP81rya0UY4/s1600/2.jpg" /> <span class="left"><h3> HEADING HERE</h3> DESCRIPTION HERE</span> </li> <li class="btrix_slider3Image"> <img src="http://1.bp.blogspot.com/-3is-vmPTmGI/UWftkffjuHI/AAAAAAAAC3g/snGy5UH5zkw/s1600/3.png" /> <span class="top"><h3> HEADING HERE</h3> DESCRIPTION HERE</span> </li> <li class="btrix_slider3Image"> <img src="http://4.bp.blogspot.com/-rHjVa2jba_U/UWftlBmpHhI/AAAAAAAAC3w/8yMencJfHNY/s1600/5.jpg" /> <span class="bottom"><h3> HEADING HERE</h3> DESCRIPTION HERE</span> </li> <li class="btrix_slider3Image"> <img src="http://1.bp.blogspot.com/-f-3f9LZRVgg/UWftlJ5iqqI/AAAAAAAAC30/RzkkgDEe9bM/s1600/4.png" /> <span class="bottom"><h3> HEADING HERE</h3> DESCRIPTION HERE</span> </li> <div class="clear btrix_slider3Image"> </div> </ul> </div> <br /> <!--Code at www.allbloggingtricks.com-->
And drag this widget from sidebar to above the Blog Posts area as in figure below.
Finally click
Save arrangement
and see the result on your blog.
Modification
Replace HEADING HERE and DESCRIPTION HERE with corresponding image details.
If you want to use different image, change all URL with other image URLs.
If you have further query or suggestion related to this topic, you can make comment below.
3 notes · View notes
innovaturelabs · 4 years
Text
Security Solutions for PHP
PHP is as secure a language as any other programming language. It’s an open source server side scripting language that has various attributes and frameworks which requires programmers to write and engineer secure applications.
In PHP there are several areas where security issues appear more frequently. Malicious users can exploit these vulnerabilities to gain sensitive information about your system or your users.
These vulnerabilities can include:
Injection
Broken Authentication
Sensitive Data Exposure
Broken Access control
Cross Site Scripting (XSS)
Insecure Deserialization
PHP also relies on several third-party libraries which can have security vulnerabilities. If the application is using the vulnerable library version, then the application also may be vulnerable too.
Injection
A code injection happens when an attacker sends invalid data to the web application with the intention to make it do something that the application was not designed/programmed to do.
Perhaps the most common example around this security vulnerability is the SQL query consuming untrusted data. You can see one example below:
String query = “SELECT * FROM accounts WHERE custID = ‘” + request.getParameter(“id”) + “‘”;
This query can be made use of by calling up the web page executing it with the following URL: http://example.com/app/accountView?id=’ or ‘1’=’1 causing the return of all the rows stored on the database table.
The core of a code injection is the lack of validation of the data used by the web applications which means that this weakness can be present on almost any type of technology.
Following are the recommendations to prevent SQL injections
Use positive or “whitelist” server-side input validation.
For any residual dynamic queries, escape special characters using the specific escape syntax for that interpreter.
Use LIMIT and other SQL controls within queries to prevent mass disclosure of records in case of SQL injection.
Broken Authentication
A broken authentication can allow an attacker to use manual and/or automatic methods to try to gain control over any account they want in a system — or even worse — to gain complete control over the system. These threats can come in many forms. A web application contains a broken authentication threats if it:
Permits automated threats such as credential stuffing, where the hacker has a list of valid usernames and passwords.
Permits brute force or other automated threats.
Permits default, weak, or well-known common passwords.
Uses common text, encrypted, or weakly hashed passwords.
Has missing or ineffective multi-factor authentication.
Shown session IDs in the URL (e.g., URL rewriting).
Following are the recommended preventive measures.
Where the other possible way is the implementation of multi-factor authentication to prevent automated, credential stuffing, brute force, and stolen credential reuse threats.
Do not ship or make use of any default credentials, particularly for admin users.
Implement weak-password checks
Use a server-side, secure, built-in session manager that generates a new random session ID with high entropy after login. Session IDs should not be in the URL. Ids should also be securely stored and invalidated after logout, idle, and absolute timeouts.
Sensitive Data Exposure
Over the last few years, sensitive data exposure has been one of the most common threat around the world. Some sensitive data that needs protection is Credentials, Credit card numbers, Social Security Numbers, Medical information, Personally, identifiable information (PII), Other personal information. This threat is usually very hard to make use of; however, the consequences of a successful attack are dreadful.
There are two types of data:
Stored data — data at rest
Transmitted data — data that is transmitted internally between servers, or to web browsers
Both types of data should be protected. When thinking about data in transit, one way to protect it on a website is by having an SSL certificate. Not encrypting sensitive data is the main reason why these attacks are still so widespread.
Some of the ways to prevent data exposure are:
Do not store sensitive data unnecessarily.
Discard it as soon as possible or use PCI DSS compliant tokenization or even shorten. Data that is not retained cannot be stolen.
Make sure to encrypt all possible sensitive data at rest.
Ensure up-to-date and strong standardized algorithms, protocols, and keys are in place; use proper key management.
Disable caching for responses that contain sensitive data.
Store passwords using strong adaptive and salted hashing functions with a work factor (delay factor), such as bcrypt
Broken Access Control
Access controls are mainly designed to prevent users from acting outside their intended permissions, when threats exist in these controls, or there are no controls users can act outside of their intended permissions. This may help attackers to steal information from other users, modify data and perform actions as other users. Broken access controls can make applications at a high-risk for compromise, typically resulting in the impact of confidentiality and integrity of data. An adversary can steal information accessed by users of the application, exploit data by performing actions that various user roles can perform within the application, and in certain circumstances compromise the web server.
Common access control vulnerabilities include:
Bypassing access control ensure by modifying the URL, internal application state, or the HTML page, or simply using a custom API attack tool
providing the primary key to be changed to another’s users record, permitting viewing or editing someone else’s account.
upgrading of privilege.
Metadata exploitation, such as replaying or tampering with a JSON Web Token (JWT) access control token or a cookie or hidden field exploited to elevate privileges, or abusing JWT invalidation
CORS misconfiguration allows unauthorized API access.
Force browsing to authenticated pages as an unauthenticated user or to advanced pages as a standard user. Entering API with missing access controls for POST, PUT and DELETE.
The technical recommendations to prevent broken access control are:
Except for public resources, deny by default.
Executing access control mechanisms once and reuse them throughout the application, including minimizing CORS usage.
Model access controls should enforce record ownership instead of accepting that the user can create, read, update, or delete any record.
Defuse web server directory listing and ensure file metadata (e.g. git) and backup files even if they are not present within web roots.
Maintain log access control failures, alert admins when appropriate (e.g. repeated failures).
Developers and QA staff should include functional access control units and integration tests.
Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS) is the most used common singular security threat existing in web applications at large. XSS occurs when an attacker can inject a script, often JavaScript, into the output of a web application in such a way that it is executed in the client browser. This ordinarily happens by locating a means of breaking out of a data context in HTML into a scripting context — usually by injecting new HTML, JavaScript strings or CSS markup. HTML has no shortage of locations in which executable JavaScript can be injected and browsers have even managed to add more. The injection is sent to the web application via any means of input such as HTTP parameters.
Injected JavaScript can be used to accomplish quite a lot: stealing cookie and session information, performing HTTP requests with the user’s session, redirecting users to hostile websites, accessing and manipulating client-side persistent storage, performing complex calculations and returning results to an attacker’s server, attacking the browser or installing malware, leveraging control of the user interface via the DOM to perform a UI Redress (aka Clickjacking) attack, rewriting or manipulating in-browser applications, attacking browser extensions, and the list goes on…possibly forever.
Some preventive measures to reduce the chances of XSS attacks:
Using the frameworks that automatically escape XSS by design.
Escaping untrusted HTTP request data based on the context in the HTML output will resolve Reflected and Stored XSS vulnerabilities.
Put in context-sensitive encoding when modifying the browser document on the client side acts against DOM XSS.
Allowing a content security policy (CSP) is a defense-in-depth mitigating control against XSS.
Insecure Deserialization
There should be a way to transform the in-memory object into a stream of bytes which can be easily stored and shared. That is what the process of serialization is all about. When the game performs the serialization of an object, we say that the object is serialized.
Tumblr media
The following function in php to perform the mutation of object to bytes is as follows:
$my_object = serialize($variable);
Deserialization is the opposite of serialization. In fact, it consists of converting the serialized data into an in-memory representation which the software can then manipulate. If we want to retrieve the state of the serialized character object, it needs to deserialize it first.
Tumblr media
The following function in php to perform the mutation from bytes to object is as follows:
$my_bytes = unserialize($variable);
When a software deserializes user-maintained data without verification, we call it insecure deserialization. If the developer does not perform a verification before deserialization, the insecure deserialization will trigger the attacker’s code.
The best way to protect your web application from this type of risk is not to accept serialized objects from untrusted sources.
Following are some recommendations that you can try to implement:
Performing integrity checks such as digital signatures on any serialized objects to prevent hostile object creation or data tampering.
Impose strict type constraints during deserialization before object creation as the code typically expects a definable set of classes.
Separating and running code that deserializes in low privilege environments when possible.
Logging exceptions and failures, such as where the incoming type is not the expected type, or the deserialization throws exceptions.
Limiting or monitoring incoming and outgoing network connectivity from containers or servers that deserialize.
Monitoring deserialization, alerting if a user deserializes constantly.
Conclusion
Security vulnerabilities are a fact of life. While a security breach can be damaging to your business, there are plenty of ways you can protect your PHP sites and mitigate your risk that don’t require you to be a security genius with the right training, awareness, tools, and practices, you can safely run PHP applications today and in future .
Tumblr media
For more information on the topic go to PHP.
0 notes
t-baba · 4 years
Photo
Tumblr media
A deep dive into the history of JavaScript
#479 — March 13, 2020
Unsubscribe  :  Read on the Web
JavaScript Weekly
Tumblr media
JavaScript: The First 20 Years — Allen Wirfs-Brock and Brendan Eich (the creator of JavaScript) have written a paper for the forthcoming History of Programming Languages Conference about how our favorite ‘sidekick scripting language for Java’ was built and has grown. It’s long, goes deep into the tech and syntax development side of things, and is sure to be my main weekend reading.
Allen Wirfs-Brock
How I Made a '3D' Game in Only 2KB of JavaScript — This is one of those detailed, fun, ‘learn a few tricks’ type walkthroughs. I’ve always been fascinated how people pull off various effects in games and how they get their code down to such small sizes. A fun read.
Frank Force
Faster CI/CD for All Your Software Projects Using Buildkite — See how Shopify scaled from 300 to 1500 engineers while keeping their build times under 5 minutes.
Buildkite sponsor
RedwoodJS: Bringing Full-Stack to the JAMstack — A new, opinionated framework that combines React, GraphQL, Prisma2, and lots more out of the box. Notably it comes from Tom Preston-Werner, one of the original founders of GitHub and the creator of Gravatar.
RedwoodJS
Why Svelte Is Our Choice for a Large Web Project in 2020 — A thorough analysis of the pros and cons of picking Svelte over, say, React or Vue.js right now.
Ryan Atkinson
Next.js 9.3 Released: The React Powered Site Building Framework — A minor point release of the popular Next framework can’t be a big deal, right? Wrong – the all new ‘Preview Mode’ (which is a game changer), smaller runtime, and new static site generation options really take things up a notch while still not introducing any breaking changes.
Next Team
⚡️ Quick Releases
Redux + TypeScript Template for Create React App 1.0
sql.js 1.2 — SQLite for the Web.
💻 Jobs
UX/Frontend Engineer @ Siteline — Join the founding engineering team at Siteline and help us revolutionize the payments process for construction.
Siteline
React + Rails Experts — Join Our Bootsrapped Remote Team — Aha! is primarily a Rails application, but we are using React to make excellent interactive experiences on top of Rails.
Aha!
Find a Dev Job Through Vettery — Vettery is completely free for job seekers. Make a profile, name your salary, and connect with hiring managers from top employers.
Vettery
📘 Articles & Tutorials
Aborting a Signal: How to Cancel an Asynchronous Task — Cancelling asynchronous tasks has always been tricky and while there’s now an official way to do so, it’s still not entirely straightforward. You might like Kyle Simpson’s CAF (Cancellable Async Flows) library to make the process easier.
Tomasz Jakut
Demystifying Async Programming in JavaScript — A lot to learn from this exploration for beginner and intermediate developers.
Yunchi Luo
Building with Web Components — The history and current state of Web Components in 2020.
Heroku sponsor
Designing the Perfect Typescript Schema Validation Library — Which, spoiler alert, has resulted in the creation of Zod, a schema validation library with static type inference.
Colin McDonnell
What is a Higher-Order Function? — You might have heard the term “higher-order function” thrown around in JS circles. This post uses some examples to attempt to define this concept.
Nick Scialli
Angular 9's Best Hidden Feature: Strict Template Checking — A lesser-known feature of Angular 9’s Ivy compiler: Find and report more errors than ever using something called ‘strict template checking.’
John Papa
How to Build a Native Desktop GIF Search App with NodeGui — Atul Ramachandran demonstrates how to install NodeGui (a Qt-driven desktop app library) and use it to build a “meme searcher.”
Atul Ramachandran
Don’t Build Your Own Analytics: Try Logi, The Only Developer-Grade Embedded Analytics Platform
Logi Analytics sponsor
Slow Code 'Hates Him'.. Optimizing a Web App from 1 to 60 FPS
Steven Waterman
Why I Don't Use Classes — “Instead of classes, I prefer modules that expose groups of functions that accept state and other dependencies.” This is a popular attitude in the JS space, to be fair.
Andy Peterson
Understanding Vue's Deep CSS Selector — Demonstrates how to use the ‘deep’ selector in Vue, a powerful tool for resolving certain CSS issues.
Marina Mosti
🔧 Code & Tools
Tumblr media
Future-Proofing Firefox’s JavaScript Debugger Implementation — A run through some of the major improvements made to JavaScript debugging in the Firefox DevTools, including garbage collection, compartments, forced returns and exceptions.
Jim Blandy and Harald Kirschner (Mozilla)
Turndown 6.0: An HTML to Markdown Conversion Library — Used to be called to-markdown. Available in both Node and browser packageable forms.
Dom Christie
Gain Real-Time Insights in Your Front-End Performance with Site24x7
Site24x7 sponsor
Code Tour: VS Code Extension to Record and Playback Guided Code Walkthroughs — This looks really promising for teams that want to help new hires get familiar with certain features of a codebase, essentially replacing actual training sessions.
VS Live Share Contrib
sort-isostring: A Tiny Utility to Sort ISO 8601 Date Strings
Luke Edwards
Uid: A Tiny Utility to Generate Random IDs of Fixed Length — Generate randomized output strings of fixed length using lowercase alphanumeric characters, for Node and the browser.
Luke Edwards
on-change: Watch an Object or Array for Changes
Sindre Sorhus
by via JavaScript Weekly https://ift.tt/2w4ypYA
0 notes
siva3155 · 5 years
Text
300+ TOP Ruby on Rails Interview Questions and Answers
Ruby on Rails Interview Questions for freshers experienced :-
1. What is Ruby on Rails? Ruby: It is an object oriented programming language inspired by PERL and PYTHON. Rails: It is a framework used for building web application 2. What is class libraries in Ruby? Class libraries in Ruby consist of a variety of domains, such as data types, thread programming, various domains, etc. 3. What is the naming convention in Rails? Variables: For declaring Variables, all letters are lowercase, and words are separated by underscores Class and Module: Modules and Classes uses MixedCase and have no underscore; each word starts with a uppercase letter Database Table: The database table name should have lowercase letters and underscore between words, and all table names should be in the plural form for example invoice_items Model: It is represented by unbroken MixedCase and always have singular with the table name Controller: Controller class names are represented in plural form, such that OrdersController would be the controller for the order table. 4. What is “Yield” in Ruby on Rails? A Ruby method that receives a code block invokes it by calling it with the “Yield”. 5. What is ORM (Object-Relationship-Model) in Rails? ORM or Object Relationship Model in Rails indicate that your classes are mapped to the table in the database, and objects are directly mapped to the rows in the table. 6. What the difference is between false and nil in Ruby? In Ruby False indicates a Boolean datatype, while Nil is not a data type, it have an object_id 4. 7. What are the positive aspects of Rails? Rails provides many features like Meta-programming: Rails uses code generation but for heavy lifting it relies on meta-programming. Ruby is considered as one of the best language for Meta-programming. Active Record: It saves object to the database through Active Record Framework. The Rails version of Active Record identifies the column in a schema and automatically binds them to your domain objects using metaprogramming Scaffolding: Rails have an ability to create scaffolding or temporary code automatically Convention over configuration: Unlike other development framework, Rails does not require much configuration, if you follow the naming convention carefully Three environments: Rails comes with three default environment testing, development, and production. Built-in-testing: It supports code called harness and fixtures that make test cases to write and execute. 8. What is the role of sub-directory app/controllers and app/helpers? App/controllers: A web request from the user is handled by the Controller. The controller sub-directory is where Rails looks to find controller classes App/helpers: The helper’s sub-directory holds any helper classes used to assist the view, model and controller classes. 9. What is the difference between String and Symbol? They both act in the same way only they differ in their behaviors which are opposite to each other. The difference lies in the object_id, memory and process tune when they are used together. Symbol belongs to the category of immutable objects whereas Strings are considered as mutable objects. 10. How Symbol is different from variables? Symbol is different from variables in following aspects It is more like a string than variable In Ruby string is mutable but a Symbol is immutable Only one copy of the symbol requires to be created Symbols are often used as the corresponding to enums in Ruby
Tumblr media
Ruby on Rails Interview Questions 11. What is Rails Active Record in Ruby on Rails? Rails active record is the Object/Relational Mapping (ORM) layer supplied with Rails. It follows the standard ORM model as Table map to classes Rows map to objects Columns map to object attributes 12. How Rails implements Ajax? Ajax powered web page retrieves the web page from the server which is new or changed unlike other web-page where you have to refresh the page to get the latest information. Rails triggers an Ajax Operation in following ways Some trigger fires: The trigger could be a user clicking on a link or button, the users inducing changes to the data in the field or on a form Web client calls the server: A Java-script method, XMLHttpRequest, sends data linked with the trigger to an action handler on the server. The data might be the ID of a checkbox, the whole form or the text in the entry field Server does process: The server side action handler does something with the data and retrieves an HTML fragment to the web client Client receives the response: The client side JavaScript, which Rails generates automatically, receives the HTML fragment and uses it to update a particular part of the current 13. How you can create a controller for subject? To create a controller for subject you can use the following command C:\ruby\library> ruby script/generate controller subject 14. What is Rails Migration? Rails Migration enables Ruby to make changes to the database schema, making it possible to use a version control system to leave things synchronized with the actual code. 15. List out what can Rails Migration do? Rails Migration can do following things Create table Drop table Rename table Add column Rename column Change column Remove column and so on 16. What is the command to create a migration? To create migration command includes C:\ruby\application>ruby script/generate migration table_name 17. When self.up and self.down method is used? When migrating to a new version, self.up method is used while self.down method is used to roll back my changes if needed. 18. What is the role of Rails Controller? The Rails controller is the logical center of the application. It faciliates the interaction between the users, views, and the model. It also performs other activities like It is capable of routing external requests to internal actions. It handles URL extremely well It regulates helper modules, which extend the capabilities of the view templates without bulking of their code It regulates sessions; that gives users the impression of an ongoing interaction with our applications 19. What is the difference between Active support’s “HashWithIndifferent” and Ruby’s “Hash” ? The Hash class in Ruby’s core library returns value by using a standard “= =” comparison on the keys. It means that the value stored for a symbol key cannot be retrieved using the equivalent string. While the HashWithIndifferentAccess treats Symbol keys and String keys as equivalent. 20. What is Cross-Site Request Forgery (CSRF) and how Rails is protected against it? CSRF is a form of attack where hacker submits a page request on your behalf to a different website, causing damage or revealing your sensitive data. To protect from CSRF attacks, you have to add “protect_from_forgery” to your ApplicationController. This will cause Rails to require a CSRF token to process the request. CSRF token is given as a hidden field in every form created using Rails form builders. 21. What is Mixin in Rails? Mixin in Ruby offers an alternative to multiple inheritances, using mixin modules can be imported inside other class. 22. How you define Instance Variable, Global Variable and Class Variable in Ruby? Ruby Instance variable begins with — @ Ruby Class variables begin with — @@ Ruby Global variables begin with — $ 23. How you can run Rails application without creating databases? You can execute your application by uncommenting the line in environment.rb path=> rootpath conf/environment.rb config.frameworks = 24. What is the difference between the Observers and Callbacks in Ruby on Rails? Rails Observers: Observers is same as Callback, but it is used when method is not directly associated to object lifecycle. Also, the observer lives longer, and it can be detached or attached at any time. For example, displaying values from a model in the UI and updating model from user input. Rails Callback: Callbacks are methods, which can be called at certain moments of an object’s life cycle for example it can be called when an object is validated, created, updated, deleted, A call back is short lived. For example, running a thread and giving a call-back that is called when thread terminates 25. What is rake in Rails? Rake is a Ruby Make; it is a Ruby utility that substitutes the Unix utility ‘make’, and uses a ‘Rakefile’ and ‘.rake files’ to build up a list of tasks. In Rails, Rake is used for normal administration tasks like migrating the database through scripts, loading a schema into the database, etc. 26. How you can list all routes for an application? To list out all routes for an application you can write rake routes in the terminal. 27. What is sweeper in Rails? Sweepers are responsible for expiring or terminating caches when model object changes. 28. Mention the log that has to be seen to report errors in Ruby Rails? Rails will report errors from Apache in the log/Apache.log and errors from the Ruby code in log/development.log. 29. What is the difference between Dynamic and Static Scaffolding? Dynamic Scaffolding Static Scaffolding It automatically creates the entire content and user interface at runtime It enables to generation of new, delete, edit methods for the use in application It does not need a database to be synchronized It requires manual entry in the command to create the data with their fields It does not require any such generation to take place It requires the database to be migrated 30. What is the function of garbage collection in Ruby on Rails? The functions of garbage collection in Ruby on Rails includes It enables the removal of the pointer values which is left behind when the execution of the program ends It frees the programmer from tracking the object that is being created dynamically on runtime It gives the advantage of removing the inaccessible objects from the memory, and allows other processes to use the memory 31. What is the difference between redirect and render in Ruby on Rails? Redirect is a method that is used to issue the error message in case the page is not issued or found to the browser. It tells browser to process and issue a new request. Render is a method used to make the content. Render only works when the controller is being set up properly with the variables that require to be rendered. 32. What is the purpose of RJs in Rails? RJs is a template that produces JavaScript which is run in an eval block by the browser in response to an AJAX request. It is sometimes used to define the JavaScript, Prototype and helpers provided by Rails. 33. What is Polymorphic Association in Ruby on Rails? Polymorphic Association allows an ActiveRecord object to be connected with Multiple ActiveRecord objects. A perfect example of Polymorphic Association is a social site where users can comment on anywhere whether it is a videos, photos, link, status updates etc. It would be not feasible if you have to create an individual comment like photos_comments, videos_comment and so on. 34. What are the limits of Ruby on Rails? Ruby on Rails has been designed for creating a CRUD web application using MVC. This might make Rails not useful for other programmers. Some of the features that Rails does not support include Foreign key in databases Linking to multiple data-base at once Soap web services Connection to multiple data-base servers at once 35. What is the difference between calling super() and super call? super(): A call to super() invokes the parent method without any arguments, as presumably expected. As always, being explicit in your code is a good thing. super call: A call to super invokes the parent method with the same arguments that were passed to the child method. An error will therefore occur if the arguments passed to the child method don’t match what the parent is expecting. 36. What about Dig, Float and Max? Float class is used whenever the function changes constantly. Dig is used whenever you want to represent a float in decimal digits. Max is used whenever there is a huge need of Float. 37. How can we define Ruby regular expressions? Ruby regular expression is a special sequence of characters that helps you match or find other strings. A regular expression literal is a pattern between arbitrary delimiters or slashes followed by %r. 38. What is the defined operator? Define operator states whether a passed expression is defined or not. If the expression is defined, it returns the description string and if it is not defined it returns a null value. 39. List out the few features of Ruby? Free format – You can start writing from program from any line and column Case sensitive – The uppercase and lowercase letters are distinct Comments – Anything followed by an unquoted #, to the end of the line on which it appears, is ignored by the interpreter Statement delimiters- Multiple statements on one line must be separated by semicolons, but they are not required at the end of a line. 40. Mention the types of variables available in Ruby Class? Types of variables available in Ruby Class are, Local Variables Global Variables Class Variables Instance Variables 41. How can you declare a block in Ruby? In Ruby, the code in the block is always enclosed within braces ({}). You can invoke a block by using “yield statement”. 42. What is the difference between put and putc statement? Unlike the puts statement, which outputs the entire string onto the screen. The Putc statement can be used to output one character at a time. 43. What is a class library in Ruby? Ruby class libraries consist of a variety of domains, such as thread programming, data types, various domains, etc. These classes give flexible capabilities at a high level of abstraction, giving you the ability to create powerful Ruby scripts useful in a variety of problem domains. The following domains which have relevant class libraries are, GUI programming Network programming CGI Programming Text processing 44. In Ruby, it explains about the defined operator? The defined operator tells whether a passed expression is defined or not. If the expression is not defined, it gives null, and if the expression is defined it returns the description string. 45. What is the difference in scope for these two variables: @@name and @name? The difference in scope for these two variables is that: @@name is a class variable @name is an instance variable 46. What is the syntax for Ruby collect Iterator? The syntax for Ruby collect Iterator collection = collection.collect. 47. In Ruby code, often it is observed that coder uses a short hand form of using an expression like array.map(&:method_name) instead of array.map { |element| element.method_name }. How this trick actually works? When a parameter is passed with “&” in front of it. Ruby will call to_proc on it in an attempt to make it usable as a block. So, symbol to_Proc will invoke the method of the corresponding name on whatever is passed to it. Thus helping our shorthand trick to work. 48. What is Interpolation in Ruby? Ruby Interpolation is the process of inserting a string into a literal. By placing a Hash (#) within {} open and close brackets, one can interpolate a string into the literal. 49. What is the Notation used for denoting class variables in Ruby? In Ruby, A constant should begin with an uppercase letter, and it should not be defined inside a method A local must begin with the _ underscore sign or a lowercase letter A global variable should begin with the $ sign. An uninitialized global has the value of “nil” and it should raise a warning. It can be referred anywhere in the program. A class variable should begin with double @@ and have to be first initialized before being used in a method definition 50. What is the difference between Procs and Blocks? The difference between Procs and Blocks, Block is just the part of the syntax of a method while proc has the characteristics of a block Procs are objects, blocks are not At most one block can appear in an argument list Only block is not able to be stored into a variable while Proc can 51. What is the difference between a single quote and double quote? A single-quoted strings don’t process ASCII escape codes, and they don’t do string interpolation. 52. What is the difference between a gem and a plugin in Ruby? Gem: A gem is a just ruby code. It is installed on a machine, and it’s available for all ruby applications running on that machine. Plugin: Plugin is also ruby code, but it is installed in the application folder and only available for that specific application. 53. What is the difference extend and include? The “include” makes the module’s methods available to the instance of a class, while “extend” makes these methods available to the class itself. 54. Why Ruby on Rails? There are lot of advantages of using ruby on rails: 1. DRY Principal 2. Convention over Configuration 3. Gems and Plugins 4. Scaffolding 5. Pure OOP Concept 6. Rest Support 7. Rack support 8. Action Mailer 9. Rpc support 10. Rexml Support 11. etc.. 55. What is the Difference between Symbol and String? Symbol are same like string but both behaviors is different based on object_id, memory and process time (cpu time) Strings are mutable , Symbols are immutable. Mutable objects can be changed after assignment while immutable objects can only be overwritten. For example p "string object jak".object_id #=> 22956070 p "string object jak".object_id #=> 22956030 p "string object jak".object_id #=> 22956090 p :symbol_object_jak.object_id #=> 247378 p :symbol_object_jak.object_id #=> 247378 p :symbol_object_jak.object_id #=> 247378 p " string object jak ".to_sym.object_id #=> 247518 p " string object jak ".to_sym.object_id #=> 247518 p " string object jak ".to_sym.object_id #=> 247518 p :symbol_object_jak.to_s.object_id #=> 22704460 p :symbol_object_jak.to_s.object_id #=> 22687010 p :symbol_object_jak.to_s.object_id #=> 21141310 And also it will differ by process time For example: Testing two symbol values for equality (or non-equality) is faster than testing two string values for equality, Note : Each unique string value has an associated symbol 56. What things we can define in the model? There are lot of things you can define in models few are: 1. Validations (like validates_presence_of, numeracility_of, format_of etc.) 2. Relationships(like has_one, has_many, HABTM etc.) 3. Callbacks(like before_save, after_save, before_create etc.) 4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model 5. ROR Queries in Sql 6. Active record Associations Relationship 57. What do you mean by the term Rail Migration? It is basically an approach with the help of which the users can make the changes to the already existing database Schema in Ruby and can implement a version control system. The main aim is to synchronize the objects to get the quality outcomes. 58. What exactly do you know about the Rail Observers? It is very much similar to that of Callback. They can be deployed directly in case the methods are not integrated with the lifecycle of the object. It is possible for the users to attach the observer to any file and perform the reverse action by the user. 59. Name the two types of Scaffolding in the Ruby? These are Static and Dynamic Scaffolding 60. Explain some of the looping structures available in Ruby? For loop, While loop, Until Loop. Be able to explain situations in which you would use one over another. Ruby on Rails Questions and Answers Pdf Download Read the full article
0 notes
mbaljeetsingh · 5 years
Text
Using Netlify Forms and Netlify Functions to Build an Email Sign-Up Widget
Building and maintaining your own website is a great idea. Not only do you own your platform, but you get to experiment with web technologies along the way. Recently, I dug into a concept called serverless functions, starting with my own website. I’d like to share the results and what I learned along the way, so you can get your hands dirty, too!
But first, a 1-minute intro to serverless functions
A serverless function (sometimes called a lambda function or cloud function) is a piece of code that you can write, host, and run independently of your website, app, or any other code. Despite the name, serverless functions do, indeed, run on a server; but it’s a server you don’t have to build or maintain. Serverless functions are exciting because they take a lot of the legwork out of making powerful, scalable, apps.
There’s lots of great information on serverless functions out there, and a great place to start is CSS Trick’s own guide: The Power of Serverless Front-End Developers.
The Challenge: Build a Mailing List Sign Up Form
I started my journey with a challenge: I wanted to have an email list sign-up form on my site. The rules are as follows:
It should work without JavaScript. I’d like to see how much I can get by with just CSS and HTML. Progressive enhancements are OK.
It shouldn’t require external dependencies. This is a learning project, so I want to write 100% of the code if possible.
It should use serverless functions. Instead of sending data to my email list service client-side, let’s do it server(less)-side!
Meet the team: 11ty, Netlify, and Buttondown
My website is built using a static site framework called 11ty. 11ty allows me to write templates and components in HTML, so that’s how we’ll build our email form. (Chris recently wrote a great article about his experience with 11ty if you’re interested in learning more.)
The website is then deployed using a service called Netlify) and it is the key player on our team here: the point guard, the quarterback, the captain. That’s because Netlify has three features that work together to produce serverless excellence:
Netlify can deploy automatically from a GitHub repo. This means I can write my code, create a pull request, and instantly see if my code works. While there are tools to test serverless functions locally, Netlify makes it super easy to test live.
Netlify Forms handles any form submissions my site gets. This is one part of the serverless equation: instead of writing code to collect submissions, I’ll configure the HTML with a few simple attributes and let Netlify handle the rest.
Netlify Functions allows me to take action with the data from my forms. I’ll write some code to send emails off to my email list provider, and tell Netlify when to run that code.
Finally, I’ll manage my email list with a service called Buttondown. It’s a no-frills email newsletter provider, with an easy-to-use API.
Bonus: for personal sites like mine, 11ty, Netlify, and Buttondown are free. You can’t beat that.
The form
The HTML for my email subscription form is very minimal, with a few extras for Netlify Forms to work.
<form class="email-form" name="newsletter" method="POST" data-netlify="true" netlify-honeypot="bot-field"> <div hidden aria-hidden="true"> <label> Don’t fill this out if you're human: <input name="bot-field" /> </label> </div> <label for="email">Your email address</label> <div> <input type="email" name="email" placeholder="Email" id="email" required /> <button type="submit">Subscribe</button> </div> </form>
First, I set the data-netlify attribute to true to tell Netlify to handle this form.
The first input in the form is named bot-field. This tricks robots into revealing themselves: I tell Netlify to watch for any suspicious submissions by setting the netlify-honeypot attribute to bot-field. I then hide the field from humans using the html hidden and aria-hidden values — users with and without assistive technology won’t be able to fill out the fake input.
If the form gets submitted with anything in the bot-field input, Netlify knows it’s coming from a robot, and ignores the input. In addition to this layer of protection, Netlify automatically filters suspicious submissions with Askimethttps://ift.tt/2LXyCDl). I don’t have to worry about spam!
The next input in the form is named email. This is where the email address goes! I’ve specified the input-type as email, and indicated that is required; this means that the browser will do all my validation for me, and won’t let users submit anything other than a valid email address.
Tumblr media
Progressive enhancement with JavaScript
One neat feature of Netlify Forms is the ability to automatically redirect users to a “thank you” page when they submit a form. But ideally, I’d like to keep my users on the page. I wrote a short function to submit the form without a redirect.
const processForm = form => { const data = new FormData(form) data.append('form-name', 'newsletter'); fetch('/', { method: 'POST', body: data, }) .then(() => { form.innerHTML = `<div class="form--success">Almost there! Check your inbox for a confirmation e-mail.</div>`; }) .catch(error => { form.innerHTML = `<div class="form--error">Error: ${error}</div>`; }) }
When I provide the content of my email form to this function via the form value, it submits the form using JavaScript’s built-in Fetch API. If the function was successful, it shows a pleasant message to the user. If the function hits a snag, it’ll tell my users that something went wrong.
This function is called whenever a user clicks the “submit” button on the form:
const emailForm = document.querySelector('.email-form') if (emailForm) { emailForm.addEventListener('submit', e => { e.preventDefault(); processForm(emailForm); }) }
This listener progressively enhances the default behavior of the form. This means that if the user has JavaScript disabled, the form still works!
Tumblr media
The serverless function
Now that we have a working email submission form, it’s time to do some automation with a serverless function.
The way Netlify functions work is as follows:
Write the function in a JavaScript file in your project.
Tell Netlify where to look for your function via the netlify.toml file in your project.
Add any environment variables you’ll need via Netlify’s admin interface. An environment variable is something like an API key that you need to keep secret.
That’s it! The next time you deploy your site, the function will be ready to go.
The function for my site is going to be in the functions folder, so I have the following in my netlify.toml file:
[build] base = "." functions = "./functions"
Then, I’ll add a file in the functions folder called submission-created.js. It’s important to name the file submission-created so that Netlify knows to run it every time a new form submission occurs. A full list of events you can script against can be found in Netlify’s documentation. If you’ve correctly named and configured your function, you should see it on Netlify’s Functions dashboard:
Tumblr media
Netlify’s Functions dashboard shows I’ve correctly configured my submission-created function
The content in submission-created.js looks like this:
require('dotenv').config() const fetch = require('node-fetch') const { EMAIL_TOKEN } = process.env exports.handler = async event => { const email = JSON.parse(event.body).payload.email console.log(`Recieved a submission: ${email}`) return fetch('https://api.buttondown.email/v1/subscribers', { method: 'POST', headers: { Authorization: `Token ${EMAIL_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ email }), }) .then(response => response.json()) .then(data => { console.log(`Submitted to Buttondown:\n ${data}`) }) .catch(error => ({ statusCode: 422, body: String(error) })) }
Let’s look at this line-by-line.
Line 1 includes a library called dotenv. This will help me use environment variables. Environment variables are useful to hold information that I don’t want to make public, like an API key. If I’m running my project locally, I set my environment variables with a .env file in the repo, and make sure it’s listed my .gitignore file. In order to deploy on Netlify, I also set up environment variables in Netlify’s web interface.
Tumblr media
On line 2, I add a small library called node-fetch. This allows me to use Javascript’s Fetch API in node, which is how we’ll send data to Buttondown. Netlify automatically includes this dependency, as long as it’s listed in my project’s package.json file.
On line 3, I import my API key from the environment variables object, process.env.
Line 4 is where the function is defined. The exports.handler value is where Netlify expects to find our function, so we define it there. The only input we’ll need is the event value, which will contain all of the data from the form submission.
After retrieving the email address from the event value using JSON.parse, I’m ready to send it off to Buttondown. Here’s where I use the node-fetch library I imported earlier: I send a POST request to https://api.buttondown.email/v1/subscribers, including my API key in the header. Buttondown’s API doesn’t have many features, so it doesn’t take long to read through the documentation if you’d like to learn more.
The body of my POST request consists of the email address we retrieved.
Then (using the neat .then() syntax), I collect the response from Buttondown’s server. I do this so I can diagnose any issues that are happening with the process — Netlify makes it easy to check your function’s logs, so use console.log often!
Tumblr media
Deploying the function
Now that I’ve written my function, configured my netlify.toml file, and added my environment variables, everything is ready to go. Deploying is painless: just set up Netlify’s GitHub integration, and your function will be deployed when your project is pushed.
Netlify projects can also be tested locally using Netlify Dev. Depending on the complexity of your code, it can be faster to develop locally: just run npm i netlify -g, then netlify dev. Netlify Dev will use the netlify.toml file to configure and run the project locally, including any serverless functions. Neat, right? One caveat: Netlify Dev currently can’t trigger serverless functions on form submissions, so you’ll have to test that using preview builds.
An idea for the future
Buttondown’s API has a few possible responses when I submit a new email. For instance, if a user submits an email that’s already subscribed to the list, I’d love to be able to tell them as soon as they submit the form.
Conclusion
All in all, I only had to write about 50 lines of code to have a functional email newsletter sign-up form available on my website. I wrote it all in HTML, CSS, and JavaScript, without having to fret with the server side of the equation. The form handles spam, and my readers get a nice experience whether they have JavaScript enabled or not.
The post Using Netlify Forms and Netlify Functions to Build an Email Sign-Up Widget appeared first on CSS-Tricks.
via CSS-Tricks https://ift.tt/2YEuPRd
0 notes