Javascript techniques used for cold calls

Source: Internet
Author: User

The front-end is already playing bad! It's no longer a piece of news that uses javascript that is similar to garbled code to create a graph and can run normally, like using the | Operator to assign default values to variables is also well known. Today I saw a post on Quora, And I instantly got a lot of front-end skills, some of which are tips, some are unknown cold knowledge, which cannot be digested for a while. Now we have sorted it out and shared it with you. We have also added some of the usual accumulated and extended content.

JavaScript code in the address bar of an HTML Browser

Many people should still know that JavaScript code can be directly run in the browser address bar. The method is to start with javascript: followed by the statement to be executed. For example:

javascript:alert('hello from address bar :)');

Paste the above Code to the address bar of the browser and press Enter. Then alert runs normally, and a pop-up window appears.

Note that if you copy the paste code to the address bar of the browser, IE and Chrome will automatically remove the javascript at the beginning of the Code:, so you need to manually add it to execute it correctly, while Firefox does not automatically remove it, it does not support running JS code in the address bar, sigh ~

This technology is used in another blog article "Making Chrome take over email connections and making it easier to send and receive emails, use the JavaScript code in the browser address bar to set Gmail to the system's email receiver program.

Run HTML code in the browser address bar

If there are still a lot of people who know the secret above, there will be fewer people who know it. You can directly run HTML code in the address bar of a non-IE kernel browser!

For example, enter the following code in the address bar and press enter to run the code. The specified page content appears.

data:text/html,

 

Can you use a browser as an editor?

I will post the following code on the browser's address bar and paste it into the address bar. After running the code, the browser becomes a simple and original editor, just like the notepad that comes with Windows.

data:text/html, 

 

In the final analysis, thanks to the newly added contenteditable attribute in HTML5, when an element specifies this attribute, the content of the element becomes editable.

By extension, after you put the following code on the console for execution, the entire page will become editable and can be trampled at will ~

document.body.contentEditable='true';

 

Use tag a to automatically parse URLs

In many cases, we need to extract domain names, query keywords, and variable parameter values from a URL, I never expected that the browser could help us complete this task easily without writing regular expressions to capture the task. The method first creates a tag a in the JS Code, then assigns the URL to the href attribute of a, and then gets everything we want.

var a = document.createElement('a'); a.href = 'http://www.cnblogs.com/wayou/p/'; console.log(a.host);

By using this principle, we can get a more robust general method for parsing each part of the URL.

function parseURL(url) {    var a =  document.createElement('a');    a.href = url;    return {        source: url,        protocol: a.protocol.replace(':',''),        host: a.hostname,        port: a.port,        query: a.search,        params: (function(){            var ret = {},                seg = a.search.replace(/^\?/,'').split('&'),                len = seg.length, i = 0, s;            for (;i<len;i++) {                if (!seg[i]) { continue; }                s = seg[i].split('=');                ret[s[0]] = s[1];            }            return ret;        })(),        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],        hash: a.hash.replace('#',''),        path: a.pathname.replace(/^([^\/])/,'/$1'),        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],        segments: a.pathname.replace(/^\//,'').split('/')    };}
Global variables are created for elements with an ID on the page.

On an HTML page, all elements with the ID attribute set will create corresponding global variables in the JavaScript execution environment, which means that document. getElementById is redundant like a human's appendix. However, in actual projects, it is better to write exactly what you need. After all, the chance of getting rid of common code is much lower.

<div id="sample"></div><script type="text/javascript">        console.log(sample);</script>

When loading CDN files, you can save the HTTP ID

CDN is now popular, that is, loading some common JS and CSS files from specialized servers. For security reasons, some CDN servers Use HTTPS to connect, while others use traditional HTTP, in fact, we can ignore this during use and save it from the URL.

<script src="//domain.com/path/to/script.js"></script>

Use the script tag to save arbitrary Information

Set the script tag to type = 'text' and save any information in it, which can be easily obtained in JavaScript code.

<script type="text" id="template">

 

var text = document.getElementById('template').innerHTML
CSS pranks

I believe you can predict the effect after reading the following code.

*{    cursor: none!important;}

Simple text blur effect

The following two lines of simple CSS3 code can be used to blur the text. The effect is a bit like using the PS filter, so cool!

p {    color: transparent;    text-shadow: #111 0 0 5px;}

 

 

Vertical center

There have been many bloggers who have such requirements. Vertical center shows a DIV, and we know that the style text-align: center is natural in CSS. This vertical center is the only solution.

Of course, you can set the container to display: table, and set the sub-element, that is, the element to be vertically centered to display as display: table-cell, and then add vertical-align: middle, however, this implementation often damages the overall layout due to display: table, so it is better to use the table label directly.

The following style uses translate to cleverly implement the vertical center style, which requires IE9 +.

.center-vertical {    position: relative;    top: 50%;    transform: translateY(-50%);}

In comparison, horizontal center is much easier. As mentioned above, the commonly used technique of text-align: center is margin: 0 auto. However, the margin method only works when the sub-element width is smaller than the container width. This method fails when the sub-element width is greater than the container width.

As a result, left and transform can also be used to achieve horizontal center, but it is of little significance. After all, text-align and margin are almost enough to meet the requirements.

.center-horizontal {    position: relative;    left: 50%;    transform: translateX(-50%); }

 

Multiple Borders

Use repeated box-shadow to achieve the effect of Multiple Borders

/*CSS Border with Box-Shadow Example*/div {    box-shadow: 0 0 0 6px rgba(0, 0, 0, 0.2), 0 0 0 12px rgba(0, 0, 0, 0.2), 0 0 0 18px rgba(0, 0, 0, 0.2), 0 0 0 24px rgba(0, 0, 0, 0.2);    height: 200px;    margin: 50px auto;    width: 400px}

 

Real-time CSS editing

You can set the display: block style of the style label to display the style label on the page, and add the contentEditable attribute to make the style editable, the changed style effect is also updated and rendered in real time. This technique is invalid in IE. If you have this skill, do it against the day!

<!DOCTYPE html>

 

Create elements with fixed Aspect Ratio

By setting the padding-bottom of the parent window, the container can maintain a certain length ratio, which is useful in responsive page design and keeps elements unchanged.

<div style="width: 100%; position: relative; padding-bottom: 20%;">    <div style="position: absolute; left: 0; top: 0; right: 0; bottom: 0;">        this content will have a constant aspect ratio that varies based on the width.    </div></div>

 

Simple operations can also be performed in CSS.

The calc method in CSS allows you to perform some simple operations to dynamically specify the element style.

.container{background-position: calc(100% - 50px) calc(100% - 20px);}

 

JavaScript to generate random strings

Use Math. random and toString to generate random strings. The technique here is to use the toString method to receive a base number as a parameter. This base number is capped from 2 to 36. If this parameter is not specified, the base number is 10 by default. Poor!

function generateRandomAlphaNum(len) {    var rdmString = "";    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));    return rdmString.substr(0, len);}

 

Integer Operation

JavaScript does not have the concept of an integer, but it can be easily processed with a good bit operator while improving the efficiency.

| 0 and ~~ This is a good example. The two can be used to convert the floating point to an integer and the efficiency is faster than the similar parseInt, Math. round. It is useful when processing effects such as pixel and animation displacement.

Var foo = (12.4/4.13) | 0; // The result is 3var bar = ~~ (12.4/4.13); // The result is 3.

By the way ,!! Quickly convert a value to a Boolean value !! Window = true.

 

Rewrite the native browser method to implement new features

The downloaded code overwrites the browser's alert so that it can record the number of pop-up windows.

(function() {    var oldAlert = window.alert,        count = 0;    window.alert = function(a) {        count++;        oldAlert(a + "\n You've called alert " + count + " times now. Stop, it's evil!");    };})();alert("Hello World");

 

Console prank

For native method rewriting, here is a prank for everyone to have fun. Chrome's console. log supports adding styles to text, and even log images. Therefore, you can override the default log method and apply the text to be logged to the CSS blur effect. In this way, when someone tries to call the console. in log (), the ambiguous text is displayed. Cool, I said I didn't smile.

It is seen in the comments of this G + post. The effect after use is that the re-call of log will output obscure text.

var _log = console.log;console.log = function() {  _log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:transparent;text-shadow:0 0 2px rgba(0,0,0,.5);');};

 

Do not declare the value exchange of the third variable

We all know that the common practice of switching two variable values is to declare an intermediate variable for temporary storage. But there are few people who want to challenge the situation of not declaring intermediate variables. The following Code provides this implementation. Very creative.

var a=1,b=2;a=[b,b=a][0];

 

All objects

In the JavaScript world, everything is an object. Except null and undefined, other basic types of numbers, strings, and boolean values all have pairs that should be wrapped. One feature of an object is that you can call methods directly on it. For the basic numeric type, if you try to call the toString Method on it, it will fail, but the call will not fail if it is enclosed in parentheses, the internal implementation is to convert the basic type into an object with the corresponding packaging object. So (1). toString () is equivalent to new Number (1). toString (). Therefore, you can use basic types of numbers, strings, and boolean as objects, but pay attention to proper syntax.

At the same time, we noticed that the numbers in JavaScript are non-floating-point and integer. All numbers are actually floating-point, but the decimal point is omitted. For example, you can write 1 as 1 ., that's why when you try. when toString () is used, an error is reported, so the correct format should be as follows: 1 .. toString (), or add parentheses as described above. Here, brackets are used to correct the JS parser. Do not treat the dot after 1 as the decimal point. As described above, the internal implementation is to convert 1. Wrap the object into an object and then call the method.

If statement Deformation

When you need to write an if statement, try another simpler method, instead of using the logical operators in JavaScript.

Var day = (new Date). getDay () = 0; // traditional if statement if (day) {alert ('Today is Sunday! ') ;}; // Use the logic and replace ifday & alert ('Today is Sunday! ');

For example, the above Code first obtains the date of today. If it is Sunday, a window pops up. Otherwise, nothing will be done. We know that there is a short circuit in the logical operation. For the logic and expression, the result is true only when both are true. If the previous day variable is determined to be false, the result is false for the entire expression, so it will not continue to execute the subsequent alert. If the previous day is true, continue to execute the following code to determine whether the entire expression is true or false. This achieves the if effect.

For traditional if statements, if the execution body Code contains more than one statement, curly brackets are required. Using a comma expression, you can execute any code without curly brackets.

if(conditoin) alert(1),alert(2),console.log(3);

In the above if statement, if the condition is true, three operations are executed, but we do not need to enclose the three statements in curly brackets. Of course, this is not recommended. Here is the cold knowledge class :)

 

Prohibit others from loading your page with iframe

The following code is self-evident and there is nothing to say.

if (window.location != window.parent.location) window.parent.location = window.location;

 

Console. table

Chrome exclusive, IE bypass console method. The JavaScript associated array can be output to the browser console in the form of a table, the effect is amazing, the interface is very beautiful.

// Purchase status var data = [{'name': 'reuse', 'quantity ': 4}, {'product name': 'okamoto', 'qty ': 3}]; console. table (data );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.