Browser address bar running JavaScript code

Source: Internet
Author: User
Tags bitwise operators logical operators script tag dedicated server

Many people should still know that JavaScript code can be run directly in the browser's address bar, with javascript: The beginning followed by the statement to be executed. Like what:

Javascript:alert (' Hello from address bar:) ');

Paste the above code into the browser address bar return to the normal execution of alert, a popup window God now.

Note that if it is through the copy paste code to the browser address bar, IE and chrome will automatically remove the code at the beginning of the javascript:, so you need to manually add to the correct execution, and Firefox, although not automatically removed, But it doesn't support running JS code in the Address bar, sigh~

This technique is used in my other blog post, "Let Chrome take over the mail connection, send and receive mail," and use the Mail takeover program that uses JavaScript code in the browser's address bar to set Gmail as the system.

Browser address bar running HTML code

If the above little secret knows a lot of people, this rule knows less people, in the non-IE kernel browser address bar can directly run HTML code!

For example, enter the following code in the Address bar and then enter to run, the specified page content will appear.

Data:text/html,

You build it, you can put the browser as an editor

or the browser address bar on the fuss, paste the following code into the address bar after the browser becomes a primitive and simple editor, and Windows comes with the Notepad, Roar.

data:text/html, 

In the final analysis, thanks to the new contenteditable attribute in HTML5, when the element specifies the attribute, the element's content becomes editable.

By the same line, after putting the following code into the console execution, the entire page will become editable and trample on it ~

Document.body.contenteditable= ' true ';

Automatically parse URLs with a tag

Many times we have the need to extract the domain name from a URL, query the keyword, variable parameter values, and so on, and never thought that it would be easy for the browser to help us complete this task without our writing the regular to crawl. The method creates a tag in the JS code and assigns the URL that needs to be parsed 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);

With this principle, a little extension, a more robust general method of parsing the various parts of the URL is obtained. The following code comes from James ' blog.

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 ('/')     };}
The element that owns the ID of the page creates a global variable

In an HTML page, all elements that set the id attribute create the corresponding global variable in the JavaScript execution environment, which means that the document.getElementById is as redundant as the human appendix. But the best thing to do in a real project is to be honest about how to write, after all, the chances of regular code going out are much smaller.

<div id= "Sample" ></div><script type= "Text/javascript" > Console.log (sample);</script>

When loading CDN files, you can omit the HTTP identity

Now the popular CDN is to load some common JS and CSS files from a dedicated server, for security reasons, some CDN servers use HTTPS connection, and some are traditional HTTP, in fact, we can ignore this when using, it is omitted from the URL.

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

This is also mentioned in a previous translation blog, "jquery Programming Best Practices".

Save any information with the script tag

Setting the script tag to type= ' text ' can then store any information inside it, which can then be easily retrieved in JavaScript code.

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

var text = document.getElementById (' template '). InnerHTML
CSS jokes about CSS

I believe you can anticipate what happens when you finish reading the following code.

*{Cursor:none!important;}

Simple text Blur effect

The following two lines of simple CSS3 code can achieve the purpose of blurring the text, the effect is a bit like using PS filter, so cool!

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

Center vertically

There have been many bloggers have this demand, vertical center display a div, we know the CSS in the natural horizontal center of the style text-align:center. Only this vertical center has no solution.

Of course you can set the container to Display:table, and then set the child element, which is the element to be vertically centered, to Display:table-cell, and then add the Vertical-align:middle to implement it, But such implementations tend to undermine the overall layout because of display:table, so it's better to use the table tag directly.

The following style uses the translate to subtly implement the vertical center style, which needs to be ie9+.

. center-vertical {position:relative;    top:50%; Transform:translatey (-50%);}

In contrast, the horizontal center is much simpler, like the above mentioned Text-align:center, often used in the technique and margin:0 auto. But for margin Dafa it only works when the width of the child element is smaller than the width of the container, which fails when the child element width is greater than the container width.

Similarly, the use of left and transform can also achieve horizontal center, but the meaning is not big, after all, text-align and margin almost meet the demand.

. center-horizontal {position:relative;    left:50%; Transform:translatex (-50%);}

Multiple borders

The effect of multiple borders is achieved by repeating the specified Box-shadow

Online Demo

/*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}

Edit CSS in real time

The Style tab of the style label can be displayed by setting the Styles label, and with the Contenteditable property you can make the style editable, and the changed style will be rendered in real-time display:block. This technique is not valid under IE. Those who have this skill, the inverse day also!

<! DOCTYPE html>

Create a fixed aspect ratio element

By setting the Padding-bottom of the parent window, we can achieve the purpose of keeping the container in a certain length ratio, which is useful in the design of the responsive page and can keep the elements from deforming.

<div > <div > This content'll has a constant aspect ratio that varies based on the width. </div></div>

Simple arithmetic can also be done in CSS

With the Calc method in CSS, some simple operations can be performed to achieve the purpose of dynamically specifying element styles.

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

JavaScript generates random strings

Generate random strings using Math.random and ToString, from a blog post you saw a while ago. The trick here is to use the ToString method to receive a cardinality as a parameter, which is capped from 2 to 36. If not specified, the default cardinality is 10 binary. Little Dick!

function Generaterandomalphanum (len) {var rdmstring = "";    for (; rdmstring.length < len; rdmstring + = Math.random (). toString (. substr (2)); Return rdmstring.substr (0, Len);}

Operation of integers

There is no integer concept in JavaScript, but using good bitwise operators can be handled with ease, while gaining efficiency gains.

| and ~ ~ is a good example of using both to convert a floating point into an integer and to be more efficient than a similar parseint,math.round. It is useful when dealing with effects such as pixels and animation displacements. See this for performance comparison.

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

By the way,!! Convert a value to a Boolean value conveniently and quickly!! Window===true .

overriding native browser methods to implement new functionality

The downloaded code lets it record the number of pop-up windows by rewriting the browser's alert.

(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");

About the console prank.

About rewriting the native method, here's a prank everyone can take to find fun. Chrome's Console.log is a support for adding styles to the text, even if the log image is available. You can then rewrite the default log method to apply the text that will be log to the blur effect of the CSS, so that when someone tries to call Console.log (), it comes out with a vague text. It was so cold that I said no laughter.

It's from the comments in this g+ post. The effect after use is to call log again to output text that is illegible.

var _log = Console.log;console.log = function () {_log.call (console, '%c ' + [].slice.call (arguments)]. Join ('), ' color:tr ansparent;text-shadow:0 0 2px Rgba (0,0,0,.5); ');};

Does not declare a value exchange for a third variable

We all know the general practice of exchanging two variable values, which is to declare an intermediate variable to be staged. But there's a challenge. The following code gives the implementation of the case where the intermediate variable is not declared. It's quite creative.

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

All things are objects

In the world of JavaScript, everything is object. In addition to null and undefined, other base type numbers, strings, and Booleans have a pair of expected wrapper objects. One characteristic of an object is that you can invoke the method directly on it. For a numeric base type, when attempting to invoke the ToString method on it will fail, but the call will not fail when enclosed in parentheses, and the internal implementation is to convert the base type to the object with the corresponding wrapper object. So (1). ToString () is equivalent to new number (1). ToString (). Therefore, you can actually put the basic type number, String, Boolean etc when the object is used, just pay attention to the syntax to be decent.

At the same time, we notice that the numbers in JavaScript are floating point and shape, all the numbers are floating-point types, just omit the decimal point, such as the 1 you see can be written as 1, which is why when you try to 1.toString () will be error, So the correct wording should be this: 1.. ToString (), or, as described above, with parentheses, the function of the parentheses here is to correct the JS parser, do not take 1 points after the dot as a decimal point. The internal implementation, as described above, is to convert 1. Use wrapped object to object before calling method.

Deformation of If statement

When you need to write an if statement, you might want to try another easier way, using logical operators in JavaScript instead.

var day= (new Date). GetDay () ===0;//Traditional if statement if (day) {alert (' Today is sunday! ');};/ /use logic and replace Ifday&&alert (' Today is sunday! ');

For example, the above code, first get today's date, if it is Sunday, then pop the window, otherwise do nothing. We know that there is a short circuit in the logic operation, for the logic and expression, only the two really results are true, if the preceding day variable is judged false, then for the whole and the expression result is false, so will not continue to execute the following alert, if the front day is true, You will also continue to execute the following code to determine whether the entire expression is true or false. Use this to achieve the if effect.

For traditional if statements, if the execution code exceeds 1 statements, you need to add curly braces, and with a comma expression, you can execute any code without the curly braces.

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

In the If statement above, if the condition is true, three operations are performed, but we do not need to enclose the three lines of code in curly braces. Of course, this is not recommended, here is the cold knowledge Classroom:)

Prevent others from loading your page with an IFRAME

The following code is not self-explanatory, nothing much to say.

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

Console.table

Chrome's exclusive, IE bypass console approach. The JavaScript associative array can be output in tabular format to the browser console, and the effect is stunning and the interface is beautiful.

Purchase status var data = [{' Name ': ' Durax ', ' Quantity ': 4}, {' name ': ' Okamoto ', ' Quantity ': 3}];console.table (data);

Browser address bar running JavaScript code

Related Article

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.