'03.HTML 4.X, HTML5, XML.../HTML/Css/Script'에 해당되는 글 196건

  1. 2014.11.22 jQuery 현재날짜 세팅
  2. 2014.02.22 Javascript Closures
  3. 2014.02.22 [펌]자바스크립트의 메모리관리
  4. 2013.12.24 HTML - The <object> Element
  5. 2013.12.24 autoplay a wav file on html code
  6. 2013.10.04 javascript 자식창에 파라미터 전달 및 부모창 호출
  7. 2013.06.18 google SWFObject
  8. 2013.02.13 [펌] 자바스크립트 페이지에 오류가있을때 alert창 띄우기
  9. 2012.12.17 [펌] [공유] 코어 자바스크립트 - 강좌 모음
  10. 2012.03.15 javascript close 사용시 안내문구 없애는 방법
  11. 2010.12.30 자바스크립트 사용 예
  12. 2010.11.25 CookieUtil.js
  13. 2010.11.25 nice.nuguya.oivs.crypto.js
  14. 2010.10.26 길이체크 정규식 (아이디 비번 길이 확인)
  15. 2010.10.19 [jQuery 기본 강좌]1-3 jquery 자동완성 autocomplete 기능 쉽게 적용하기
  16. 2010.10.19 Javascript에서 String을 Number타입으로 바꾸기
  17. 2010.10.11 1.XHTML1.1 에서 사용하면 안되는 것들
  18. 2010.10.11 input 안에 'autocomplete' 사용시 w3c 에 위배되는거 수정...
  19. 2010.03.25 input index 값 구하기
  20. 2010.02.25 textarea 엔터키 수정모드 처리
  21. 2010.02.19 DES in JavaScript
  22. 2010.02.19 SHA-1 Crypt
  23. 2010.02.19 MD5 Hashing in JavaScript
  24. 2010.02.19 MD4 Hashing in JavaScript
  25. 2010.02.19 Binary to Ascii and Ascii to Binary in JavaScript
  26. 2010.02.19 Base64 Encoding/Decoding
  27. 2010.02.19 compareEndPoints() Method
  28. 2010.02.19 Transforming JavaScript Data into HTML Tables
  29. 2010.02.19 Create a table
  30. 2010.02.19 Replacing Table Cell Content
반응형


$(document).ready(function() {     $('#date').val($.datepicker.formatDate($.datepicker.ATOM, new Date())); });

 


Posted by 1010
반응형

Javascript Closures

Introduction

Closure
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Closures are one of the most powerful features of ECMAScript (javascript) but they cannot be property exploited without understanding them. They are, however, relatively easy to create, even accidentally, and their creation has potentially harmful consequences, particularly in some relatively common web browser environments. To avoid accidentally encountering the drawbacks and to take advantage of the benefits they offer it is necessary to understand their mechanism. This depends heavily on the role of scope chains in identifier resolution and so on the resolution of property names on objects.

The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

Unfortunately, properly understanding closures requires an understanding of the mechanism behind them, and quite a bit of technical detail. While some of the ECMA 262 specified algorithms have been brushed over in the early part of the following explanation, much cannot be omitted or easily simplified. Individuals familiar with object property name resolution may skip that section but only people already familiar with closures can afford to skip the following sections, and they can stop reading now and get back to exploiting them.

The Resolution of Property Names on Objects

ECMAScript recognises two categories of object, "Native Object" and "Host Object" with a sub-category of native objects called "Built-in Object" (ECMA 262 3rd Ed Section 4.3). Native objects belong to the language and host objects are provided by the environment, and may be, for example, document objects, DOM nodes and the like.

Native objects are loose and dynamic bags of named properties (some implementations are not that dynamic when it comes to the built in object sub-category, though usually that doesn't matter). The defined named properties of an object will hold a value, which may be a reference to another Object (functions are also Objects in this sense) or a primitive value: String, Number, Boolean, Null or Undefined. The Undefined primitive type is a bit odd in that it is possible to assign a value of Undefined to a property of an object but doing so does not remove that property from the object; it remains a defined named property, it just holds the value undefined.

The following is a simplified description of how property values are read and set on objects with the internal details brushed over to the greatest extent possible.

Assignment of Values

Named properties of objects can be created, or values set on existing named properties, by assigning a value to that named property. So given:-

var objectRef = new Object(); //create a generic javascript object.

A property with the name "testNumber" can be created as:-

objectRef.testNumber = 5;
/* - or:- */
objectRef["testNumber"] = 5;

The object had no "testNumber" property prior to the assignment but one is created when the assignment is made. Any subsequent assignment does not need to create the property, it just re-sets its value:-

objectRef.testNumber = 8;
/* - or:- */
objectRef["testNumber"] = 8;

Javascript objects have prototypes that can themselves be objects, as will be described shortly, and that prototype may have named properties. But this has no role in assignment. If a value is assigned and the actual object does not have a property with the corresponding name a property of that name is created and the value is assigned to it. If it has the property then its value is re-set.

Reading of Values

It is in reading values from object properties that prototypes come into play. If an object has a property with the property name used in the property accessor then the value of that property is returned:-

/* Assign a value to a named property. If the object does not have a
   property with the corresponding name prior to the assignment it
   will have one after it:-
*/
objectRef.testNumber = 8;

/* Read the value back from the property:- */

var val = objectRef.testNumber;
/* and  - val - now holds the value 8 that was just assigned to the
   named property of the object. */
   

But all objects may have prototypes, and prototypes are objects so they, in turn, may have prototypes, which may have prototypes, and so on forming what is called the prototype chain. The prototype chain ends when one of the objects in the chain has a null prototype. The default prototype for the Object constructor has a null prototype so:-

var objectRef = new Object(); //create a generic javascript object.

Creates an object with the prototype Object.prototype that itself has a null prototype. So the prototype chain for objectRef contains only one object: Object.prototype. However:-

/* A "constructor" function for creating objects of a -
   MyObject1 - type.
*/
function MyObject1(formalParameter){
    /* Give the constructed object a property called - testNumber - and
       assign it the value passed to the constructor as its first
       argument:-
    */
    this.testNumber = formalParameter;
}

/* A "constructor" function for creating objects of a -
   MyObject2 - type:-
*/
function MyObject2(formalParameter){
   /* Give the constructed object a property called - testString -
      and assign it the value passed to the constructor as its first
      argument:-
    */
    this.testString = formalParameter;
}

/* The next operation replaces the default prototype associated with
   all MyObject2 instances with an instance of MyObject1, passing the
   argument - 8 - to the MyObject1 constructor so that its -
   testNumber - property will be set to that value:-
*/
MyObject2.prototype = new MyObject1( 8 );

/* Finally, create an instance of - MyObject2 - and assign a reference
   to that object to the variable - objectRef - passing a string as the
   first argument for the constructor:-
*/

var objectRef = new MyObject2( "String_Value" );

The instance of MyObject2 referred to by the objectRef variable has a prototype chain. The first object in that chain is the instance of MyObject1 that was created and assigned to the prototype property of the MyObject2 constructor. The instance of MyObject1 has a prototype, the object that was assigned to the function MyObject1's prototype property by the implementation. That object has a prototype, the default Object prototype that corresponds with the object referred to by Object.prototype. Object.prototype has a null prototype so the prototype chain comes to an end at this point.

When a property accessor attempts to read a named property form the object referred to by the variable objectRef the whole prototype chain can enter into the process. In the simple case:-

var val = objectRef.testString;

- the instance of MyObject2 referred to by objectRef has a property with the name "testString" so it is the value of that property, set to "String_Value", that is assigned to the variable val. However:-

var val = objectRef.testNumber;

- cannot read a named property form the instance of MyObject2 itself as it has no such property but the variable val is set to the value of 8 rather than undefined because having failed to find a corresponding named property on the object itself the interpreter then examines the object that is its prototype. Its prototype is the instance of MyObject1 and it was created with a property named "testNumber" with the value 8 assigned to that property, so the property accessor evaluates as the value 8. Neither MyObject1 or MyObject2 have defined a toString method, but if a property accessor attempts to read the value of a toString property from objectRef:-

var val = objectRef.toString;

- the val variable is assigned a reference to a function. That function is the toString property of Object.prototype and is returned because the process of examining the prototype of objectRef, when objectRef turns out not to have a "toString" property, is acting on an object, so when that prototype is found to lack the property its prototype is examined in turn. Its prototype is Object.prototype, which does have a toString method so it is a reference to that function object that is returned.

Finally:-

var val = objectRef.madeUpProperty;

- returns undefined, because as the process of working up the prototype chain finds no properties on any of the object with the name "madeUpPeoperty" it eventually gets to the prototype of Object.prototype, which is null, and the process ends returning undefined.

The reading of named properties returns the first value found, on the object or then from its prototype chain. The assigning of a value to a named property on an object will create a property on the object itself if no corresponding property already exists.

This means that if a value was assigned as objectRef.testNumber = 3 a "testNumber" property will be created on the instance of MyObject2 itself, and any subsequent attempts to read that value will retrieve that value as set on the object. The prototype chain no longer needs to be examined to resolve the property accessor, but the instance of MyObject1 with the value of 8 assigned to its "testNumber" property is unaltered. The assignment to the objectRef object masks the corresponding property in its prototype chain.

Note: ECMAScript defines an internal [[prototype]] property of the internal Object type. This property is not directly accessible with scripts, but it is the chain of objects referred to with the internal [[prototype]] property that is used in property accessor resolution; the object's prototype chain. A public prototype property exists to allow the assignment, definition and manipulation of prototypes in association with the internal [[prototype]] property. The details of the relationship between to two are described in ECMA 262 (3rd edition) and are beyond the scope of this discussion.

Identifier Resolution, Execution Contexts and scope chains

The Execution Context

An execution context is an abstract concept used by the ECMSScript specification (ECMA 262 3rd edition) to define the behaviour required of ECMAScript implementations. The specification does not say anything about how execution contexts should be implemented but execution contexts have associated attributes that refer to specification defined structures so they might be conceived (and even implemented) as objects with properties, though not public properties.

All javascript code is executed in an execution context. Global code (code executed inline, normally as a JS file, or HTML page, loads) gets executed in global execution context, and each invocation of a function (possibly as a constructor) has an associated execution context. Code executed with the eval function also gets a distinct execution context but as eval is never normally used by javascript programmers it will not be discussed here. The specified details of execution contexts are to be found in section 10.2 of ECMA 262 (3rd edition).

When a javascript function is called it enters an execution context, if another function is called (or the same function recursively) a new execution context is created and execution enters that context for the duration of the function call. Returning to the original execution context when that called function returns. Thus running javascript code forms a stack of execution contexts.

When an execution context is created a number of things happen in a defined order. First, in the execution context of a function, an "Activation" object is created. The activation object is another specification mechanism. It can be considered as an object because it ends up having accessible named properties, but it is not a normal object as it has no prototype (at least not a defined prototype) and it cannot be directly referenced by javascript code.

The next step in the creation of the execution context for a function call is the creation of an arguments object, which is an array-like object with integer indexed members corresponding with the arguments passed to the function call, in order. It also has length and callee properties (which are not relevant to this discussion, see the spec for details). A property of the Activation object is created with the name "arguments" and a reference to the arguments object is assigned to that property.

Next the execution context is assigned a scope. A scope consists of a list (or chain) of objects. Each function object has an internal [[scope]] property (which we will go into more detail about shortly) that also consists of a list (or chain) of objects. The scope that is assigned to the execution context of a function call consists of the list referred to by the [[scope]] property of the corresponding function object with the Activation object added at the front of the chain (or the top of the list).

Then the process of "variable instantiation" takes place using an object that ECMA 262 refers to as the "Variable" object. However, the Activation object is used as the Variable object (note this, it is important: they are the same object). Named properties of the Variable object are created for each of the function's formal parameters, and if arguments to the function call correspond with those parameters the values of those arguments are assigned to the properties (otherwise the assigned value is undefined). Inner function definitions are used to create function objects which are assigned to properties of the Variable object with names that correspond to the function name used in the function declaration. The last stage of variable instantiation is to create named properties of the Variable object that correspond with all the local variables declared within the function.

The properties created on the Variable object that correspond with declared local variables are initially assigned undefined values during variable instantiation, the actual initialisation of local variables does not happen until the evaluation of the corresponding assignment expressions during the execution of the function body code.

It is the fact that the Activation object, with its arguments property, and the Variable object, with named properties corresponding with function local variables, are the same object, that allows the identifier arguments to be treated as if it was a function local variable.

Finally a value is assigned for use with the this keyword. If the value assigned refers to an object then property accessors prefixed with the this keyword reference properties of that object. If the value assigned (internally) is null then the this keyword will refer to the global object.

The global execution context gets some slightly different handling as it does not have arguments so it does not need a defined Activation object to refer to them. The global execution context does need a scope and its scope chain consists of exactly one object, the global object. The global execution context does go through variable instantiation, its inner functions are the normal top level function declarations that make up the bulk of javascript code. The global object is used as the Variable object, which is why globally declared functions become properties of the global object. As do globally declared variables.

The global execution context also uses a reference to the global object for the this object.

scope chains and [[scope]]

The scope chain of the execution context for a function call is constructed by adding the execution context's Activation/Variable object to the front of the scope chain held in the function object's [[scope]] property, so it is important to understand how the internal [[scope]] property is defined.

In ECMAScript functions are objects, they are created during variable instantiation from function declarations, during the evaluation of function expressions or by invoking the Function constructor.

Function objects created with the Function constructor always have a [[scope]] property referring to a scope chain that only contains the global object.

Function objects created with function declarations or function expressions have the scope chain of the execution context in which they are created assigned to their internal [[scope]] property.

In the simplest case of a global function declaration such as:-

function exampleFunction(formalParameter){
    ...   // function body code
}

- the corresponding function object is created during the variable instantiation for the global execution context. The global execution context has a scope chain consisting of only the global object. Thus the function object that is created and referred to by the property of the global object with the name "exampleFunction" is assigned an internal [[scope]] property referring to a scope chain containing only the global object.

A similar scope chain is assigned when a function expression is executed in the global context:-

var exampleFuncRef = function(){
    ...   // function body code
}

- except in this case a named property of the global object is created during variable instantiation for the global execution context but the function object is not created, and a reference to it assigned to the named property of the global object, until the assignment expression is evaluated. But the creation of the function object still happens in the global execution context so the [[scope]] property of the created function object still only contains the global object in the assigned scope chain.

Inner function declarations and expressions result in function objects being created within the execution context of a function so they get more elaborate scope chains. Consider the following code, which defines a function with an inner function declaration and then executes the outer function:-

function exampleOuterFunction(formalParameter){
    function exampleInnerFuncitonDec(){
        ... // inner function body
    }
    ...  // the rest of the outer function body.
}

exampleOuterFunction( 5 );

The function object corresponding with the outer function declaration is created during variable instantiation in the global execution context so its [[scope]] property contains the one item scope chain with only the global object in it.

When the global code executes the call to the exampleOuterFunction a new execution context is created for that function call and an Activation/Variable object along with it. The scope of that new execution context becomes the chain consisting of the new Activation object followed by the chain refereed to by the outer function object's [[scope]] property (just the global object). Variable instantiation for that new execution context results in the creation of a function object that corresponds with the inner function definition and the [[scope]] property of that function object is assigned the value of the scope from the execution context in which it was created. A scope chain that contains the Activation object followed by the global object.

So far this is all automatic and controlled by the structure and execution of the source code. The scope chain of the execution context defines the [[scope]] properties of the function objects created and the [[scope]] properties of the function objects define the scope for their execution contexts (along with the corresponding Activation object). But ECMAScript provides the with statement as a means of modifying the scope chain.

The with statement evaluates an expression and if that expression is an object it is added to the scope chain of the current execution context (in front of the Activation/Variable object). The with statement then executes another statement (that may itself be a block statement) and then restores the execution context's scope chainto what it was before.

A function declaration could not be affected by a with statement as they result in the creation of function objects during variable instantiation, but a function expression can be evaluated inside a with statement:-

/* create a global variable - y - that refers to an object:- */
var y = {x:5}; // object literal with an - x - property
function exampleFuncWith(){
    var z;
    /* Add the object referred to by the global variable - y - to the
       front of he scope chain:-
    */
    with(y){
        /* evaluate a function expression to create a function object
           and assign a reference to that function object to the local
           variable - z - :-
        */
        z = function(){
            ... // inner function expression body;
        }
    }
    ... 
}

/* execute the - exampleFuncWith - function:- */
exampleFuncWith();

When the exampleFuncWith function is called the resulting execution context has a scope chain consisting of its Activation object followed by the global object. The execution of the with statement adds the object referred to by the global variable y to the front of that scope chain during the evaluation of the function expression. The function object created by the evaluation of the function expression is assigned a [[scope]] property that corresponds with the scope of the execution context in which it is created. A scope chain consisting of object y followed by the Activation object from the execution context of the outer function call, followed by the global object.

When the block statement associated with the with statement terminates the scope of the execution context is restored (the y object is removed), but the function object has been created at that point and its [[scope]] property assigned a reference to a scope chain with the y object at its head.

Identifier Resolution

Identifiers are resolved against the scope chain. ECMA 262 categorises this as a keyword rather than an identifier, which is not unreasonable as it is always resolved dependent on the this value in the execution context in which it is used, without reference to the scope chain.

Identifier resolution starts with the first object in the scope chain. It is checked to see if it has a property with a name that corresponds with the identifier. Because the scope chain is a chain of objects this checking encompasses the prototype chain of that object (if it has one). If no corresponding value can be found on the first object in the scope chain the search progresses to the next object. And so on until one of the objects in the chain (or one of its prototypes) has a property with a name that corresponds with the identifier or the scope chain is exhausted.

The operation on the identifier happens in the same way as the use of property accessors on objects described above. The object identified in the scope chain as having the corresponding property takes the place of the object in the property accessor and the identifier acts as a property name for that object. The global object is always at the end of the scope chain.

As execution contexts associated with function calls will have the Activation/Variable object at the front of the chain, identifiers used in function bodies are effectively first checked to see whether they correspond with formal parameters, inner function declaration names or local variables. Those would be resolved as named properties of the Activation/Variable object.

Closures

Automatic Garbage Collection

ECMAScript uses automatic garbage collection. The specification does not define the details, leaving that to the implementers to sort out, and some implementations are known to give a very low priority to their garbage collection operations. But the general idea is that if an object becomes un-referable (by having no remaining references to it left accessible to executing code) it becomes available for garbage collection and will at some future point be destroyed and any resources it is consuming freed and returned to the system for re-use.

This would normally be the case upon exiting an execution context. The scope chain structure, the Activation/Variable object and any objects created within the execution context, including function objects, would no longer be accessible and so would become available for garbage collection.

Forming Closures

A closure is formed by returning a function object that was created within an execution context of a function call from that function call and assigning a reference to that inner function to a property of another object. Or by directly assigning a reference to such a function object to, for example, a global variable, a property of a globally accessible object or an object passed by reference as an argument to the outer function call. e.g:-

function exampleClosureForm(arg1, arg2){
    var localVar = 8;
    function exampleReturned(innerArg){
        return ((arg1 + arg2)/(innerArg + localVar));
    }
    /* return a reference to the inner function defined as -
       exampleReturned -:-
    */
    return exampleReturned;
}

var globalVar = exampleClosureForm(2, 4);

Now the function object created within the execution context of the call to exampleClosureForm cannot be garbage collected because it is referred to by a global variable and is still accessible, it can even be executed with globalVar(n).

But something a little more complicated has happened because the function object now referred to by globalVar was created with a [[scope]] property referring to a scope chain containing the Activation/Variable object belonging to the execution context in which it was created (and the global object). Now the Activation/Variable object cannot be garbage collected either as the execution of the function object referred to by globalVar will need to add the whole scope chain from its [[scope]] property to the scope of the execution context created for each call to it.

A closure is formed. The inner function object has the free variables and the Activation/Variable object on the function's scope chain is the environment that binds them.

The Activation/Variable object is trapped by being referred to in the scope chain assigned to the internal [[scope]] property of the function object now referred to by the globalVar variable. The Activation/Variable object is preserved along with its state; the values of its properties. Scope resolution in the execution context of calls to the inner function will resolve identifiers that correspond with named properties of that Activation/Variable object as properties of that object. The value of those properties can still be read and set even though the execution context for which it was created has exited.

In the example above that Activation/Variable object has a state that represents the values of formal parameters, inner function definitions and local variables, at the time when the outer function returned (exited its execution context). The arg1 property has the value 2,the arg2 property the value 4, localVar the value 8 and an exampleReturned property that is a reference to the inner function object that was returned form the outer function. (We will be referring to this Activation/Variable object as "ActOuter1" in later discussion, for convenience.)

If the exampleClosureForm function was called again as:-

var secondGlobalVar = exampleClosureForm(12, 3);

- a new execution context would be created, along with a new Activation object. And a new function object would be returned, with its own distinct [[scope]] property referring to a scope chain containing the Activation object form this second execution context, with arg1 being 12 and arg2 being 3. (We will be referring to this Activation/Variable object as "ActOuter2" in later discussion, for convenience.)

A second and distinct closure has been formed by the second execution of exampleClosureForm.

The two function objects created by the execution of exampleClosureForm to which references have been assigned to the global variable globalVar and secondGlobalVar respectively, return the expression ((arg1 + arg2)/(innerArg + localVar)). Which applies various operators to four identifiers. How these identifiers are resolved is critical to the use and value of closures.

Consider the execution of the function object referred to by globalVar, as globalVar(2). A new execution context is created and an Activation object (we will call it "ActInner1"), which is added to the head of the scope chain referred to the [[scope]] property of the executed function object. ActInner1 is given a property named innerArg, after its formal parameter and the argument value 2 assigned to it. The scope chain for this new execution context is: ActInner1-> ActOuter1-> global object.

Identifier resolution is done against the scope chain so in order to return the value of the expression ((arg1 + arg2)/(innerArg + localVar)) the values of the identifiers will be determined by looking for properties, with names corresponding with the identifiers, on each object in the scope chain in turn.

The first object in the chain is ActInner1 and it has a property named innerArg with the value 2. All of the other 3 identifiers correspond with named properties of ActOuter1; arg1 is 2, arg2 is 4 and localVar is 8. The function call returns ((2 + 4)/(2 + 8)).

Compare that with the execution of the otherwise identical function object referred to by secondGlobalVar, as secondGlobalVar(5). Calling the Activation object for this new execution context "ActInner2", the scope chain becomes: ActInner2-> ActOuter2-> global object. ActInner2 returns innerArg as 5 and ActOuter2 returns arg1, arg2 and localVar as 12, 3 and 8 respectively. The value returned is ((12 + 3)/(5 + 8)).

Execute secondGlobalVar again and a new Activation object will appear at the front of the scope chain but ActOuter2 will still be next object in the chain and the value of its named properties will again be used in the resolution of the identifiers arg1, arg2 and localVar.

This is how ECMAScript inner functions gain, and maintain, access to the formal parameters, declared inner functions and local variables of the execution context in which they were created. And it is how the forming of a closure allows such a function object to keep referring to those values, reading and writing to them, for as long as it continues to exist. The Activation/Variable object from the execution context in which the inner function was created remains on the scope chain referred to by the function object's [[scope]] property, until all references to the inner function are freed and the function object is made available for garbage collection (along with any now unneeded objects on its scope chain).

Inner function may themselves have inner functions, and the inner functions returned from the execution of functions to form closures may themselves return inner functions and form closures of their own. With each nesting the scope chain gains extra Activation objects originating with the execution contexts in which the inner function objects were created. The ECMAScript specification requires a scope chain to be finite, but imposes no limits on their length. Implementations probably do impose some practical limitation but no specific magnitude has yet been reported. The potential for nesting inner functions seems so far to have exceeded anyone's desire to code them.

What can be done with Closures?

Strangely the answer to that appears to be anything and everything. I am told that closures enable ECMAScript to emulate anything, so the limitation is the ability to conceive and implement the emulation. That is a bit esoteric and it is probably better to start with something a little more practical.

Example 1: setTimeout with Function References

A common use for a closure is to provide parameters for the execution of a function prior to the execution of that function. For example, when a function is to be provided as the first argument to the setTimout function that is common in web browser environments.

setTimeout schedules the execution of a function (or a string of javascript source code, but not in this context), provided as its first argument, after an interval expressed in milliseconds (as its second argument). If a piece of code wants to use setTimeout it calls the setTimeout function and passes a reference to a function object as the first argument and the millisecond interval as the second, but a reference to a function object cannot provide parameters for the scheduled execution of that function.

However, code could call another function that returned a reference to an inner function object, with that inner function object being passed by reference to the setTimeout function. The parameters to be used for the execution of the inner function are passed with the call to the function that returns it. setTimout executes the inner function without passing arguments but that inner function can still access the parameters provided by the call to the outer function that returned it:-

function callLater(paramA, paramB, paramC){
    /* Return a reference to an anonymous inner function created
       with a function expression:-
    */
    return (function(){
        /* This inner function is to be executed with - setTimeout
           - and when it is executed it can read, and act upon, the
           parameters passed to the outer function:-
        */
        paramA[paramB] = paramC;
    });
}

...

/* Call the function that will return a reference to the inner function
   object created in its execution context. Passing the parameters that
   the inner function will use when it is eventually executed as
   arguments to the outer function. The returned reference to the inner
   function object is assigned to a local variable:-
*/
var functRef = callLater(elStyle, "display", "none");
/* Call the setTimeout function, passing the reference to the inner
   function assigned to the - functRef - variable as the first argument:-
*/
hideMenu=setTimeout(functRef, 500);

Example 2: Associating Functions with Object Instance Methods

There are many other circumstances when a reference to a function object is assigned so that it would be executed at some future time where it is useful to provide parameters for the execution of that function that would not be easily available at the time of execution but cannot be known until the moment of assignment.

One example might be a javascript object that is designed to encapsulate the interactions with a particular DOM element. It has doOnClick, doMouseOver and doMouseOut methods and wants to execute those methods when the corresponding events are triggered on the DOM element, but there may be any number of instances of the javascript object created associated with different DOM elements and the individual object instances do not know how they will be employed by the code that instantiated them. The object instances do not know how to reference themselves globally because they do not know which global variables (if any) will be assigned references to their instances.

So the problem is to execute an event handling function that has an association with a particular instance of the javascript object, and knows which method of that object to call.

The following example uses a small generalised closure based function that associates object instances with element event handlers. Arranging that the execution of the event handler calls the specified method of the object instance, passing the event object and a reference to the associated element on to the object method and returning the method's return value.

/* A general function that associates an object instance with an event
   handler. The returned inner function is used as the event handler.
   The object instance is passed as the - obj - parameter and the name
   of the method that is to be called on that object is passed as the -
   methodName - (string) parameter.
*/
function associateObjWithEvent(obj, methodName){
    /* The returned inner function is intended to act as an event
       handler for a DOM element:-
    */
    return (function(e){
        /* The event object that will have been parsed as the - e -
           parameter on DOM standard browsers is normalised to the IE
           event object if it has not been passed as an argument to the
           event handling inner function:-
        */
        e = e||window.event;
        /* The event handler calls a method of the object - obj - with
           the name held in the string - methodName - passing the now
           normalised event object and a reference to the element to
           which the event handler has been assigned using the - this -
           (which works because the inner function is executed as a
           method of that element because it has been assigned as an
           event handler):-
        */
        return obj[methodName](e, this);
    });
}

/* This constructor function creates objects that associates themselves
   with DOM elements whose IDs are passed to the constructor as a
   string. The object instances want to arrange than when the
   corresponding element triggers onclick, onmouseover and onmouseout
   events corresponding methods are called on their object instance.
*/
function DhtmlObject(elementId){
    /* A function is called that retrieves a reference to the DOM
       element (or null if it cannot be found) with the ID of the
       required element passed as its argument. The returned value
       is assigned to the local variable - el -:-
    */
    var el = getElementWithId(elementId);
    /* The value of - el - is internally type-converted to boolean for
       the - if - statement so that if it refers to an object the
       result will be true, and if it is null the result false. So that
       the following block is only executed if the - el - variable
       refers to a DOM element:-
    */
    if(el){
        /* To assign a function as the element's event handler this
           object calls the - associateObjWithEvent - function
           specifying itself (with the - this - keyword) as the object
           on which a method is to be called and providing the name of
           the method that is to be called. The - associateObjWithEvent
           - function will return a reference to an inner function that
           is assigned to the event handler of the DOM element. That
           inner function will call the required method on the
           javascript object when it is executed in response to
           events:-
        */
        el.onclick = associateObjWithEvent(this, "doOnClick");
        el.onmouseover = associateObjWithEvent(this, "doMouseOver");
        el.onmouseout = associateObjWithEvent(this, "doMouseOut");
        ...
    }
}
DhtmlObject.prototype.doOnClick = function(event, element){
    ... // doOnClick method body.
}
DhtmlObject.prototype.doMouseOver = function(event, element){
    ... // doMouseOver method body.
}
DhtmlObject.prototype.doMouseOut = function(event, element){
    ... // doMouseOut method body.
}

And so any instances of the DhtmlObject can associate themselves with the DOM element that they are interested in without any need to know anything about how they are being employed by other code, impacting on the global namespace or risking clashes with other instances of the DhtmlObject.

Example 3: Encapsulating Related Functionality

Closures can be used to create additional scopes that can be used to group interrelated and dependent code in a way that minimises the risk of accidental interaction. Suppose a function is to build a string and to avoid the repeated concatenation operations (and the creation of numerous intermediate strings) the desire is to use an array to store the parts of the string in sequence and then output the results using the Array.prototype.join method (with an empty string as its argument). The array is going to act as a buffer for the output, but defining it locally to the function will result in its re-creation on each execution of the function, which may not be necessary if the only variable content of that array will be re-assigned on each function call.

One approach might make the array a global variable so that it can be re-used without being re-created. But the consequences of that will be that, in addition to the global variable that refers to the function that will use the buffer array, there will be a second global property that refers to the array itself. The effect is to render the code less manageable, as, if it is to be used elsewhere, its author has to remember to include both the function definition and the array definition. It also makes the code less easy to integrate with other code because instead of just ensuring that the function name is unique within the global namespace it is necessary to ensure that the Array on which it is dependent is using a name that is unique within the global namespace.

A Closure allows the buffer array to be associated (and neatly packaged) with the function that is dependent upon it and simultaneously keep the property name to which the buffer array as assigned out of the global namespace and free of the risk of name conflicts and accidental interactions.

The trick here is to create one additional execution context by executing a function expression in-line and have that function expression return an inner function that will be the function that is used by external code. The buffer array is then defined as a local variable of the function expression that is executed in-line. That only happens once so the Array is only created once, but is available to the function that depends on it for repeated use.

The following code creates a function that will return a string of HTML, much of which is constant, but those constant character sequences need to be interspersed with variable information provided as parameter to the function call.

A reference to an inner function object is returned from the in-line execution of a function expression and assigned to a global variable so that it can be called as a global function. The buffer array is defined as a local variable in the outer function expression. It is not exposed in the global namespace and does not need to be re-created whenever the function that uses it is called.

/* A global variable - getImgInPositionedDivHtml - is declared and
   assigned the value of an inner function expression returned from
   a one-time call to an outer function expression.

   That inner function returns a string of HTML that represents an
   absolutely positioned DIV wrapped round an IMG element, such that
   all of the variable attribute values are provided as parameters
   to the function call:-
*/
var getImgInPositionedDivHtml = (function(){
    /* The - buffAr - Array is assigned to a local variable of the
       outer function expression. It is only created once and that one
       instance of the array is available to the inner function so that
       it can be used on each execution of that inner function.

       Empty strings are used as placeholders for the date that is to
       be inserted into the Array by the inner function:-
    */
    var buffAr = [
        '<div id="',
        '',   //index 1, DIV ID attribute
        '" style="position:absolute;top:',
        '',   //index 3, DIV top position
        'px;left:',
        '',   //index 5, DIV left position
        'px;width:',
        '',   //index 7, DIV width
        'px;height:',
        '',   //index 9, DIV height
        'px;overflow:hidden;\"><img src=\"',
        '',   //index 11, IMG URL
        '\" width=\"',
        '',   //index 13, IMG width
        '\" height=\"',
        '',   //index 15, IMG height
        '\" alt=\"',
        '',   //index 17, IMG alt text
        '\"><\/div>'
    ];
    /* Return the inner function object that is the result of the
       evaluation of a function expression. It is this inner function
       object that will be executed on each call to -
       getImgInPositionedDivHtml( ... ) -:-
    */
    return (function(url, id, width, height, top, left, altText){
        /* Assign the various parameters to the corresponding
           locations in the buffer array:-
        */
        buffAr[1] = id;
        buffAr[3] = top;
        buffAr[5] = left;
        buffAr[13] = (buffAr[7] = width);
        buffAr[15] = (buffAr[9] = height);
        buffAr[11] = url;
        buffAr[17] = altText;
        /* Return the string created by joining each element in the
           array using an empty string (which is the same as just
           joining the elements together):-
        */
        return buffAr.join('');
    }); //:End of inner function expression.
})();
/*^^- :The inline execution of the outer function expression. */

If one function was dependent on one (or several) other functions, but those other functions were not expected to be directly employed by any other code, then the same technique could be used to group those functions with the one that was to be publicly exposed. Making a complex multi-function process into an easily portable and encapsulated unit of code.

Other Examples

Probably one of the best known applications of closures is Douglas Crockford's technique for the emulation of private instance variables in ECMAScript objects. Which can be extended to all sorts of structures of scope contained nested accessibility/visibility, including the emulation of private static members for ECMAScript objects.

The possible application of closures are endless, understanding how they work is probably the best guide to realising how they can be used.

Accidental Closures

Rendering any inner function accessible outside of the body of the function in which it was created will form a closure. That makes closures very easy to create and one of the consequences is that javascript authors who do not appreciate closures as a language feature can observe the use of inner functions for various tasks and employ inner functions, with no apparent consequences, not realising that closures are being created or what the implications of doing that are.

Accidentally creating closures can have harmful side effects as the following section on the IE memory leak problem describes, but they can also impact of the efficiency of code. It is not the closures themselves, indeed carefully used they can contribute significantly towards the creation of efficient code. It is the use of inner functions that can impact on efficiency.

A common situation is where inner functions are used is as event handlers for DOM elements. For example the following code might be used to add an onclick handler to a link element:-

/* Define the global variable that is to have its value added to the
   - href - of a link as a query string by the following function:-
*/
var quantaty = 5;
/* When a link passed to this function (as the argument to the function
   call - linkRef -) an onclick event handler is added to the link that
   will add the value of a global variable - quantaty - to the - href -
   of that link as a query string, then return true so that the link
   will navigate to the resource specified by the - href - which will
   by then include the assigned query string:-
*/
function addGlobalQueryOnClick(linkRef){
    /* If the - linkRef - parameter can be type converted to true
       (which it will if it refers to an object):-
    */
    if(linkRef){
        /* Evaluate a function expression and assign a reference to the
           function object that is created by the evaluation of the
           function expression to the onclick handler of the link
           element:-
        */
        linkRef.onclick = function(){
            /* This inner function expression adds the query string to
               the - href - of the element to which it is attached as
               an event handler:-
            */
            this.href += ('?quantaty='+escape(quantaty));
            return true;
        };
    }
}

Whenever the addGlobalQueryOnClick function is called a new inner function is created (and a closure formed by its assignment). From the efficiency point of view that would not be significant if the addGlobalQueryOnClick function was only called once or twice, but if the function was heavily employed many distinct function objects would be created (one for each evaluation of the inner function expression).

The above code is not taking advantage of the fact that inner functions are becoming accessible outside of the function in which they are being created (or the resulting closures). As a result exactly the same effect could be achieved by defining the function that is to be used as the event handler separately and then assigning a reference to that function to the event handling property. Only one function object would be created and all of the elements that use that event handler would share a reference to that one function:-

/* Define the global variable that is to have its value added to the
   - href - of a link as a query string by the following function:-
*/
var quantaty = 5;

/* When a link passed to this function (as the argument to the function
   call - linkRef -) an onclick event handler is added to the link that
   will add the value of a global variable - quantaty - to the - href -
   of that link as a query string, then return true so that the link
   will navigate to the resource specified by the - href - which will
   by then include the assigned query string:-
*/
function addGlobalQueryOnClick(linkRef){
    /* If the - linkRef - parameter can be type converted to true
       (which it will if it refers to an object):-
    */
    if(linkRef){
        /* Assign a reference to a global function to the event
           handling property of the link so that it becomes the
           element's event handler:-
        */
        linkRef.onclick = forAddQueryOnClick;
    }
}
/* A global function declaration for a function that is intended to act
   as an event handler for a link element, adding the value of a global
   variable to the - href - of an element as an event handler:-
*/
function forAddQueryOnClick(){
    this.href += ('?quantaty='+escape(quantaty));
    return true;
}

As the inner function in the first version is not being used to exploit the closures produced by its use, it would be more efficient not to use an inner function, and thus not repeat the process of creating many essentially identical function objects.

A similar consideration applies to object constructor functions. It is not uncommon to see code similar to the following skeleton constructor:-

function ExampleConst(param){
    /* Create methods of the object by evaluating function expressions
       and assigning references to the resulting function objects
       to the properties of the object being created:-
    */
    this.method1 = function(){
        ... // method body.
    };
    this.method2 = function(){
        ... // method body.
    };
    this.method3 = function(){
        ... // method body.
    };
    /* Assign the constructor's parameter to a property of the object:-
    */
    this.publicProp = param;
}

Each time the constructor is used to create an object, with new ExampleConst(n), a new set of function objects are created to act as its methods. So the more object instances that are created the more function objects are created to go with them.

Douglas Crockford's technique for emulating private members on javascript objects exploits the closure resulting form assigning references to inner function objects to the public properties of a constructed object from within its constructor. But if the methods of an object are not taking advantage of the closure that they will form within the constructor the creation of multiple function objects for each object instantiation will make the instantiation process slower and more resources will be consumed to accommodate the extra function objects created.

In that case it would be more efficient to create the function object once and assign references to them to the corresponding properties of the constructor's prototype so they may be shared by all of the objects created with that constructor:-

function ExampleConst(param){
    /* Assign the constructor's parameter to a property of the object:-
    */
    this.publicProp = param;
}
/* Create methods for the objects by evaluating function expressions
   and assigning references to the resulting function objects to the
   properties of the constructor's prototype:-
*/
ExampleConst.prototype.method1 = function(){
    ... // method body.
};
ExampleConst.prototype.method2 = function(){
    ... // method body.
};
ExampleConst.prototype.method3 = function(){
    ... // method body.
};

The Internet Explorer Memory Leak Problem

The Internet Explorer web browser (verified on versions 4 to 6 (6 is current at the time of writing)) has a fault in its garbage collection system that prevents it from garbage collecting ECMAScript and some host objects if those host objects form part of a "circular" reference. The host objects in question are any DOM Nodes (including the document object and its descendants) and ActiveX objects. If a circular reference is formed including one or more of them, then none of the objects involved will be freed until the browser is closed down, and the memory that they consume will be unavailable to the system until that happens.

A circular reference is when two or more objects refer to each other in a way that can be followed and lead back to the starting point. Such as object 1 has a property that refers to object 2, object 2 has a property that refers to object 3 and object 3 has a property that refers back to object 1. With pure ECMAScript objects as soon as no other objects refer to any of objects 1, 2 or 3 the fact that they only refer to each other is recognised and they are made available for garbage collection. But on Internet Explorer, if any of those objects happen to be a DOM Node or ActiveX object, the garbage collection cannot see that the circular relationship between them is isolated from the rest of the system and free them. Instead they all stay in memory until the browser is closed.

Closures are extremely good at forming circular references. If a function object that forms a closure is assigned as, for example, and event handler on a DOM Node, and a reference to that Node is assigned to one of the Activation/Variable objects in its scope chain then a circular reference exists. DOM_Node.onevent -> function_object.[[scope]] -> scope_chain -> Activation_object.nodeRef -> DOM_Node. It is very easy to do, and a bit of browsing around a site that forms such a reference in a piece of code common to each page can consume most of the systems memory (possibly all).

Care can be taken to avoid forming circular references and remedial action can be taken when they cannot otherwise be avoided, such as using IE's onunload event to null event handling function references. Recognising the problem and understanding closures (and their mechanism) is the key to avoiding this problem with IE.

comp.lang.javascript FAQ notes T.O.C.

  • Written by Richard Cornford. March 2004.
  • With corrections and suggestions by:-
    • Martin Honnen.
    • Yann-Erwan Perio (Yep).
    • Lasse Reichstein Nielsen. (definition of closure)
    • Mike Scirocco.
    • Dr John Stockton.
    • Garrett Smith.

 

Posted by 1010
반응형

자바스크립트의 메모리관리

개요

C 언어같은 저급 언어는 메모리 관리를 위해 malloc() 과 free()를 사용한다. 반면, 자바스크립트는 무언가가 생성되었을 때(오브젝트나 문자열 등) 메모리를 할당하고 쓸모 없어졌을 때 '자동으로' free 한다. '자동으로' 라는 말에는 혼란의 여지가 있다. 이는 자바스크립트를 포함한 여러 고급 언어 개발자들에게 메모리 관리가 불가능하다는 인상을 준다. 하지만 실상은 그렇지 않다.  

메모리 생존주기

메모리 생존주기는 프로그래밍 언어와 관계없이 비슷하다.

  1. 필요할때 할당한다.
  2. 사용한다. (읽기, 쓰기)
  3. 필요없어지면 해제한다. 

첫 번째 부분과 두 번째 부분은 모든 언어에서 분명하게 기술되지만 마지막 부분은 조금 다르다. 저급 언어에서는 분명히 기술되지만 자바스크립트 같은 고급 언어에서는 분명하게 기술되지 않는다(역자: 명시적으로 free를 하지 않는다는 의미). 

자바스크립트에서 메모리 할당

값 초기화

자바스크립트에서는 프로그래머들이 일일히 메모리 할당을 하는 수고를 덜어주기위해 값을 선언할 때 메모리를 할당한다. 

var n = 123; // 정수를 담기 위한 메모리 할당
var s = "azerty"; // 문자열을 담기 위한 메모리 할당

var o = {
  a: 1,
  b: null
}; // 오브젝트와 그 오브젝트에 포함된 값들을 담기 위한 메모리 할당

var a = [1, null, "abra"]; // (오브젝트 처럼) 배열과 배열에 담긴 값들을 위한 메모리 할당

function f(a){
  return a + 2;
} // 함수를 위한 할당(함수는 '호출가능한' 오브젝트이다)

// 함수식 또한 오브젝트를 담기위한 메모리를 할당한다. 
someElement.addEventListener('click', function(){
  someElement.style.backgroundColor = 'blue';
}, false);

함수 호출을 통한 할당

몇 가지 함수에서도 메모리 할당이 일어난다. 

var d = new Date();
var e = document.createElement('div'); // DOM 엘리먼트를 위해 메모리를 할당한다.

몇 가지 메쏘드도 새로운 값이나 오브젝트를 담기 위해 메모리 할당이 일어난다.

var s = "azerty";
var s2 = s.substr(0, 3); // s2는 새로운 문자열
// 자바스크립트에서 문자열은 immutable 값이기 때문에 메모리를 새로 할당하지 않고 단순히 [0, 3] 이라는 범위만 저장한다. 

var a = ["ouais ouais", "nan nan"];
var a2 = ["generation", "nan nan"];
var a3 = a.concat(a2); // 4개의 원소를 가진 새로운 배열

값 사용

값 사용이란 기본적으로는 할당된 메모리를 읽고 쓰는 것을 의미한다. 변수나 오브젝트 속성 값을 읽고 쓸때 값 사용이 일어난다. 또 함수 호출시 함수에 인수를 넘길때도 일어난다. 

할당된 메모리가 더 이상 필요없을 때 해제하기

이 단계에서 대부분의 문제가 발생한다. "할당된 메모리가 더 이상 필요없을 때"를 알아내기가 힘들기 때문이다. 이제까지는 개발자들이 메모리가 필요없어질 때를 정하고 free하곤 했다. 

고급 언어 인터프리터는 "가비지 콜렉터"라는 소프트웨어를 가지고 있다. 가비지 콜렉터란 메모리 할당을 추적하고 할당된 메모리가 더 이상 필요 없어졌을 때 해제하는 작업을 한다. 이 작업은 근사적인 작업이다. 왜냐하면 일반적인 경우에 어떤 메모리가 필요없는지 알아내는 것은 알고리즘으로 풀 수 없는 비결정적인 문제이기 때문이다. (역자: 세상에 존재하는 모든 가비지 콜렉터는 안전하지만 완전하지 않다. 가비지 콜렉터는 항상 필요없어진 메모리만을 해제하지만 모든 필요없어진 메모리를 해제하는건 아니다)

가비지 콜렉션

위에서 언급한 것처럼 "더 이상 필요없는" 모든 메모리를 찾는건 비결정적이다. 따라서 몇 가지 제한을 두어 "더 이상 필요없는 모든 메모리"가 아니라 "더 이상 필요없는 몇몇 메모리"를 찾아보자. 몇 개의 가비지 콜렉션 알고리즘을 소개하고 한계점을 알아볼 것이다.

참조

가비지 콜렉션 알고리즘의 핵심 개념은 참조이다. A라는 메모리를 통해 (명시적이든 암시적이든) B라는 메모리에 접근할 수 있다면 "B는 A에 참조된다" 라고 한다. 예를 들어 모든 자바스크립트 오브젝트는 prototype 을 암시적으로 참조하고 그 오브젝트의 속성을 명시적으로 참조한다.

앞으로 "오브젝트"라는 어휘의 의미를 넓혀서 기존의 자바스크립트 오브젝트뿐만 아니라 함수 스코프도 포괄하자.

참조-세기(Reference-counting) 가비지 콜렉션

참조-세기 알고리즘은 가장 무난한 알고리즘이다. 이 알고리즘은 "더 이상 필요없는 오브젝트"를 "어떤 다른 오브젝트도 참조하지 않는 오브젝트"라고 정의한다. 어떤 오브젝트를 참조하는 다른 오브젝트가 하나도 없다면 그 오브젝트에 대해 가비지 콜렉션을 수행한다.

예제

var o = { 
  a: {
    b:2
  }
}; // 2개의 오브젝트가 생성되었다. 하나의 오브젝트는 다른 오브젝트의 속성으로 참조된다.
// 나머지 하나는 'o' 변수에 할당되었다.
// 명백하게 가비지 콜렉션 수행될 메모리는 하나도 없다.


var o2 = o; // 'o2' 변수는 위의 오브젝트를 참조하는 두 번째 변수이다.
o = 1; // 이제 'o2' 변수가 위의 오브젝트를 참조하는 유일한 변수가 되었다.

var oa = o2.a; // 위의 오브젝트의 'a' 속성을 참조했다.
// 이제 'o2.a'는 두 개의 참조를 가진다. 'o2'가 속성으로 참조하고 'oa'라는 변수가 참조한다.

o2 = "yo"; // 이제 맨 처음 'o' 변수가 참조했던 오브젝트를 참조하는 오브젝트는 없다(역자: 참조하는 유일한 변수였던 o2에 다른 값을 대입했다)
// 이제 오브젝트에 가비지 콜렉션이 수행될 수 있을까?
// 아니다. 오브젝트의 'a' 속성이 여전히 'oa' 변수에 의해 참조되므로 메모리를 해제할 수 없다.

oa = null; // 'oa' 변수에 다른 값을 할당했다. 이제 맨 처음 'o' 변수가 참조했던 오브젝트를 참조하는 다른 변수는 없으므로 가비지 콜렉션이 수행된다.

한계: 순환

이 알고리즘은 두 오브젝트가 서로를 참조하면 문제가 발생한다. 두 오브젝트 모두 필요 없어졌더라도 가비지 콜렉션을 수행할 수 없다.

function f(){
  var o = {};
  var o2 = {};
  o.a = o2; // o는 o2를 참조한다.
  o2.a = o; // o2는 o를 참조한다.

  return "azerty";
}

f();
// 두 오브젝트가 만들어지고 서로를 참조해서 순환이 일어났다.
// 함수가 종료되고 나면 사실상 두 오브젝트는 의미가 없어지므로 가비지 콜렉션이 수행되어야 한다.
// 그러나 위의 참조-세기 알고리즘에서는 두 오브젝트 모두 참조를 가지고 있기 때문에 둘 다 가비지 콜렉션이 일어나지 않는다.

실제 예제

인터넷 익스플로러 6, 7 은 DOM 오브젝트에 대해 참조-세기 알고리즘으로 가비지 콜렉션을 수행한다. 흔히, 이 두 브라우저에서는 다음과 같은 패턴의 메모리 누수가 발생한다. 

var div = document.createElement("div");
div.onclick = function(){
  doSomething();
}; // div 오브젝트는 이벤트 핸들러를 'onclick' 속성을 통해 참조한다.
// 이벤트 핸들러의 스코프에도 div 오브젝트가 있으므로 div 오브젝트에 접근할 수 있다. 따라서 이벤트 핸들러도 div 오브젝트를 참조한다.
// 순환이 발생했고 메모리 누수가 일어난다.

표시하고-쓸기(Mark-and-sweep) 알고리즘

이 알고리즘은 "더 이상 필요없는 오브젝트"를 "닿을 수 없는 오브젝트"로 정의한다.

이 알고리즘은 roots 라는 오브젝트의 집합을 가지고 있다(자바스크립트에서는 전역 변수들을 의미한다). 주기적으로 가비지 콜렉터는 roots로 부터 시작하여 roots가 참조하는 오브젝트들, roots가 참조하는 오브젝트가 참조하는 오브젝트들... 을 닿을 수 있는 오브젝트라고 표시한다. 그리고 닿을 수 있는 오브젝트가 아닌 닿을 수 없는 오브젝트에 대해 가비지 콜렉션을 수행한다.

이 알고리즘은 위에서 설명한 참조-세기 알고리즘보다 효율적이다. 왜냐하면 "참조되지 않는 오브젝트"는 모두 "닿을 수 없는 오브젝트" 이지만 역은 성립하지 않기 때문이다. 위에서 반례인 순환 참조하는 오브젝트들을 설명했다.

2012년 기준으로 모든 최신 브라우저들은 가비지 콜렉션에서 표시하고-쓸기 알고리즘을 사용한다. 지난 몇 년간 연구된 자바스크립트 가비지 콜렉션 알고리즘의 개선들은 모두 이 알고리즘에 대한 것이다. 개선된 알고리즘도 여전히 "더 이상 필요없는 오브젝트"를 "닿을 수 없는 오브젝트"로 정의하고 있다.

순환 참조는 이제 문제가 되지 않는다.

첫 번째 예제에서 함수가 리턴되고 나서 두 오브젝트는 닿을 수 없다. 따라서 가비지 콜렉션이 일어난다.

두 번째 예제에서도 마찬가지다. div 변수와 이벤트 핸들러가 roots로 부터 닿을 수 없어지면 순환 참조가 일어났음에도 불구하고 가비지 콜렉션이 일어난다.

한계: 오브젝트들은 명시적으로 닿을 수 없어져야 한다.

이 한계가 지적되었지만 실제로는 사람들은 이 문제를 비롯한 가비지 콜렉션에 별 관심이 없다.

더 보기

출처 : https://developer.mozilla.org/ko/docs/JavaScript/Memory_Management

Posted by 1010
반응형

The purpose of the <object> element is to support HTML helpers (plug-ins).


HTML Helpers (Plug-ins)

A helper application is a small computer program that extends the standard functionality of the browser. Helper applications are also called plug-ins.

Plug-ins are often used by browsers to play audio and video.

Examples of well-known plug-ins are Adobe Flash Player and QuickTime.

Plug-ins can be added to Web pages through the <object> tag or the <embed> tag. 

Most plug-ins allow manual (or programmed) control over settings for volume, rewind, forward, pause, stop, and play.


What is The Best Way to Play Audio/Video in HTML?

For the best way to embed audio or video in your Web page, please read the next chapters.


QuickTime - Play WAV Audio

Example

<object width="420" height="360"
classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="liar.wav">
<param name="controller" value="true">
</object>

Try it yourself »


 


QuickTime - Play MP4 Video

Example

<object width="420" height="360"
classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="movie.mp4">
<param name="controller" value="true">
</object>

Try it yourself »


 


Adobe Flash Player - Play SWF Video

Example

<object width="400" height="40"
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/
pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">
< param name="SRC" value="bookmark.swf">
< embed src="bookmark.swf" width="400" height="40">
< /embed>
< /object>

Try it yourself »


 


Windows Media Player - Play WMV Movie

The example below shows the suggested code used to display a Windows Media file.

Example

<object width="100%" height="100%"
type="video/x-ms-asf" url="3d.wmv" data="3d.wmv"
classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param name="url" value="3d.wmv">
<param name="filename" value="3d.wmv">
<param name="autostart" value="1">
<param name="uiMode" value="full">
<param name="autosize" value="1">
<param name="playcount" value="1">
<embed type="application/x-mplayer2" src="3d.wmv" width="100%" height="100%" autostart="true" showcontrols="true" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"></embed>
</object>

Try it yourself »


 


Plug-ins

Plug-ins can be used for many purposes: to display maps, scan for viruses, verify your bank id, and much more. The restrictions are few.

 

출처 : http://www.w3schools.com/html/html_object.asp

Posted by 1010
반응형

<!DOCTYPE html>
 <html>
 <body>

<object type="audio/x-wav" data="http://www.hydrotoys.com/wavs/Beavis_cornholio.wav" width="320" height="260">
<param name="autostart" value="true" />
<param name="controller" value="false" />
<param name="src" value="http://www.hydrotoys.com/wavs/Beavis_cornholio.wav">
</object>

<audio src="http://www.hydrotoys.com/wavs/Beavis_cornholio.wav" type="audio/x-wav" controls autoplay="autoplay">
<p>Your browser does not support the audio element </p>
<source src="http://www.hydrotoys.com/wavs/Beavis_cornholio.wav"/>
</audio>

</body>
</html>

출처 :http://stackoverflow.com/questions/12973877/autoplay-a-wav-file-on-html-code

 

Posted by 1010
반응형

부모

var retValue;
var myObject = new Object();
myObject.tempid = id; // 넘길 값

retValue = window.showModalDialog("팝업페이지", window, "dialogWidth:850px; dialogHeight:500px; center:yes; help:no; resizable:yes; scroll:no; status:no;");

function test(){

}

자식
var oMyObject = window.dialogArguments;// 팝업 실행 하는 페이지에서 값을 받아옴

temp(oMyObject.id); // 값을 넘겨줌..

부모창에 함수호출

oMyObject.test();

Posted by 1010
반응형

 

swfobject_2_2.zip

 

What is SWFObject?

SWFObject 2:

  • Offers two optimized Flash Player embed methods; a markup based approach and a method that relies on JavaScript
  • Offers a JavaScript API that aims to provide a complete tool set for embedding SWF files and retrieving Flash Player related information
  • Utilizes only one small JavaScript file (10Kb / GZIPed: 3.9Kb)
  • Is the successor of SWFObject 1.5, UFO and the Adobe Flash Player Detection Kit
  • Intends to unify all existing Flash Player embed methods and provide a new standard for embedding Adobe Flash Player content

Why should you use SWFObject?

SWFObject 2:

  • Is more optimized and flexible than any other Flash Player embed method around
  • Offers one solution for everybody: It shouldn't matter if you are an HTML, Flash, or JavaScript developer, there should be something in it for everyone
  • Breaks the cycle of being locked into vendor specific markup and promotes the use of web standards and alternative content
  • Uses unobtrusive JavaScript and JavaScript best practices
  • Is easy to use

The A List Apart article Flash Embedding Cage Match describes the full rationale behind SWFObject 2.

Why does SWFObject use JavaScript?

SWFObject 2 primarily uses JavaScript to overcome issues that cannot be solved by markup alone; it:

  • Detects the Flash Player version and determines whether Flash content or alternative content should be shown, to avoid that outdated Flash plug-ins break Flash content
  • Offers functionality to revert to alternative content in case of an outdated plug-in by means of a DOM manipulation (Note: if no Flash plug-in is installed the HTML object element automatically falls back to its nested alternative content)
  • Offers the option to use Adobe Express Install to download the latest Flash Player
  • Offers a JavaScript API to perform common Flash Player and Flash content related tasks

Should I use the static or dynamic publishing method?

SWFObject 2 offers two distinct methods to embed Flash Player content:

  1. The static publishing method embeds both Flash content and alternative content using standards compliant markup, and uses JavaScript to resolve the issues that markup alone cannot solve
  2. The dynamic publishing method is based on marked up alternative content and uses JavaScript to replace this content with Flash content if the minimal Flash Player version is installed and enough JavaScript support is available (similar like previous versions of SWFObject and UFO)

The advantages of the static publishing method are:

  1. The actual authoring of standards compliant markup is promoted
  2. Best embed performance
  3. The mechanism of embedding Flash content does not rely on a scripting language, so your Flash content can reach a significant bigger audience:
    • If you have the Flash plug-in installed, but have JavaScript disabled or a use a browser that doesn't support JavaScript, you will still be able to see your Flash content
    • Flash will now also run on a device like Sony PSP, which has very poor JavaScript support
    • Automated tools like RSS readers are able to pick up Flash content

The advantages of the dynamic publishing method are:

  1. It integrates very well with scripted applications and enables the use of dynamic variables (flashvars)
  2. It avoids click-to-activate mechanisms to activate active content in Internet Explorer 6/7 and Opera 9+. Please note that Microsoft has phased out most active content from its Internet Explorer browsers

How to embed Flash Player content using SWFObject static publishing

STEP 1: Embed both Flash content and alternative content using standards compliant markup

SWFObject's base markup uses the nested-objects method (with proprietary Internet Explorer conditional comments. See Flash Embedding Cage Match) to ensure the most optimal cross-browser support by means of markup only, while being standards compliant and supporting alternative content (See Flash Embed Test Suite):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject - step 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">
<param name="movie" value="myContent.swf" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
<!--<![endif]-->
<p>Alternative content</p>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>

</div>
</body>
</html>

NOTE: The nested-objects method requires a double object definition (the outer object targeting Internet Explorer and the inner object targeting all other browsers), so you need to define your object attributes and nested param elements twice.

Required attributes:

  • classid (outer object element only, value is always clsid:D27CDB6E-AE6D-11cf-96B8-444553540000)
  • type (inner object element only, value is always application/x-shockwave-flash)
  • data (inner object element only, defines the URL of a SWF)
  • width (both object elements, defines the width of a SWF)
  • height (both object elements, defines the height of a SWF)

Required param element:

  • movie (outer object element only, defines the URL of a SWF)

NOTE: We advise not to use the codebase attribute to point to the URL of the Flash plugin installer on Adobe's servers, because this is illegal according to the specifications which restrict its access to the domain of the current document only. We recommend the use of alternative content with a subtle message that a user can have a richer experience by downloading the Flash plugin instead.

How can you use HTML to configure your Flash content?

You can add the following often-used optional attributes to the object element:

  • id
  • name
  • class
  • align

You can use the following optional Flash specific param elements (more info):

Why should you use alternative content?

The object element allows you to nest alternative content inside of it, which will be displayed if Flash is not installed or supported. This content will also be picked up by search engines, making it a great tool for creating search-engine-friendly content. Summarizing, you should use alternative content when you like to create content that is accessible for people who browse the Web without plugins, create search-engine-friendly content or tell visitors that they can have a richer user experience by downloading the Flash plug-in.

STEP 2: Include the SWFObject JavaScript library in the head of your HTML page

The SWFObject library consists of one external JavaScript file. SWFObject will be executed as soon as it is read and will perform all DOM manipulations as soon as the DOM is loaded - for all browsers that support this, like IE, Firefox, Safari and Opera 9+ - or otherwise as soon as the onload event fires:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject - step 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<script type="text/javascript" src="swfobject.js"></script>

</head>
<body>
<div>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">
<param name="movie" value="myContent.swf" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
<!--<![endif]-->
<p>Alternative content</p>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</div>
</body>
</html>

STEP 3: Register your Flash content with the SWFObject library and tell SWFObject what to do with it

First add a unique id to the outer object tag that defines your Flash content. Second add the swfobject.registerObject method:

  1. The first argument (String, required) specifies the id used in the markup.
  2. The second argument (String, required) specifies the Flash player version your content is published for. It activates the Flash version detection for a SWF to determine whether to show Flash content or force alternative content by doing a DOM manipulation. While Flash version numbers normally consist of major.minor.release.build, SWFObject only looks at the first 3 numbers, so both "WIN 9,0,18,0" (IE) or "Shockwave Flash 9 r18" (all other browsers) will translate to "9.0.18". If you only want to test for a major version you can omit the minor and release numbers, like "9" instead of "9.0.0".
  3. The third argument (String, optional) can be used to activate Adobe express install and specifies the URL of your express install SWF file. Express install displays a standardized Flash plugin download dialog instead of your Flash content when the required plugin version is not available. A default expressInstall.swf file is packaged with the project. It also contains the corresponding expressInstall.fla and AS files (in the SRC directory) to let you create your own custom express install experience. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px.
  4. The fourth argument (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of creating a Flash plug-in <object> on the page (see API documentation)
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head>
    <title>SWFObject - step 3</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="swfobject.js"></script>

    <script type="text/javascript">
    swfobject
    .registerObject("myId", "9.0.115", "expressInstall.swf");
    </script>

    </head>
    <body>
    <div>

    <object id="myId" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="780" height="420">

    <param name="movie" value="myContent.swf" />
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data="myContent.swf" width="780" height="420">
    <!--<![endif]-->
    <p>Alternative content</p>
    <!--[if !IE]>-->
    </object>
    <!--<![endif]-->
    </object>
    </div>
    </body>
    </html>

TIPS

  • Use the SWFObject HTML and JavaScript generator to help you author your code
  • Just repeat steps 1 and 3 to embed multiple SWF files into one HTML page
  • The easiest way to reference the active object element is by using the JavaScript API: `swfobject.getObjectById(objectIdStr)

How to embed Flash Player content using SWFObject dynamic publishing

STEP 1: Create alternative content using standards compliant markup

SWFObject's dynamic embed method follows the principle of progressive enhancement and replaces alternative HTML content for Flash content when enough JavaScript and Flash plug-in support is available. First define your alternative content and label it with an id:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>

<div id="myContent">
<p>Alternative content</p>
</div>

</body>
</html>

STEP 2: Include the SWFObject JavaScript library in the head of your HTML page

The SWFObject library consists of one external JavaScript file. SWFObject will be executed as soon as it is read and will perform all DOM manipulations as soon as the DOM is loaded - for all browsers that support this, like IE, Firefox, Safari and Opera 9+ - or otherwise as soon as the onload event fires:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<script type="text/javascript" src="swfobject.js"></script>

</head>
<body>
<div id="myContent">
<p>Alternative content</p>
</div>
</body>
</html>

STEP 3: Embed your SWF with JavaScript

swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn) has five required and five optional arguments:

  1. swfUrl (String, required) specifies the URL of your SWF
  2. id (String, required) specifies the id of the HTML element (containing your alternative content) you would like to have replaced by your Flash content
  3. width (String, required) specifies the width of your SWF
  4. height (String, required) specifies the height of your SWF
  5. version (String, required) specifies the Flash player version your SWF is published for (format is: "major.minor.release" or "major")
  6. expressInstallSwfurl (String, optional) specifies the URL of your express install SWF and activates Adobe express install. Please note that express install will only fire once (the first time that it is invoked), that it is only supported by Flash Player 6.0.65 or higher on Win or Mac platforms, and that it requires a minimal SWF size of 310x137px.
  7. flashvars (Object, optional) specifies your flashvars with name:value pairs
  8. params (Object, optional) specifies your nested object element params with name:value pairs
  9. attributes (Object, optional) specifies your object's attributes with name:value pairs
  10. callbackFn (JavaScript function, optional) can be used to define a callback function that is called on both success or failure of creating a Flash plug-in <object> on the page (see API documentation)

NOTE: You can omit the optional parameters, as long as you don't break the parameter order. If you don't want to use an optional parameter, but would like to use a following optional parameter, you can simply pass false as its value. For the flashvars, params and attributes JavaScript Objects, you can also pass an empty object instead: {}.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>SWFObject dynamic embed - step 3</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="swfobject.js"></script>

<script type="text/javascript">
swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0");
</script>

</head>
<body>
<div id="myContent">
<p>Alternative content</p>
</div>
</body>
</html>

How can you configure your Flash content?

You can add the following often-used optional attributes to the object element:

  • id (NOTE: when undefined, the object element automatically inherits the id from the alternative content container element)
  • align
  • name
  • styleclass (see note about class)
  • class

Note: class is a reserved ECMA4 keyword and will throw errors in Internet Explorer unless it is surrounded by quotation marks (e.g. "class" or 'class'). For this reason, swfobject provides the styleclass keyword as a safe alternative syntax for class; if you use styleclass, swfobject will automatically insert it as class for you.

Example:

var attributes = {
id
: "myId",
align
: "left",
styleclass
: "myclass"
};

If you would rather use class instead of styleclass, wrap the word class in quotes like this:

var attributes = {
id
: "myId",
align
: "left",
"class": "myclass"
};

You can use the following optional Flash specific param elements (more info):

How do you use JavaScript Objects to define your flashvars, params and object's attributes?

You can best define JavaScript Objects using the Object literal notation, which looks like:

<script type="text/javascript">

var flashvars = {};
var params = {};
var attributes = {};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

You can add your name:value pairs while you define an object (note: please make sure not to put a comma behind the last name:value pair inside an object)

<script type="text/javascript">

var flashvars = {
name1
: "hello",
name2
: "world",
name3
: "foobar"
};
var params = {
menu
: "false"
};
var attributes = {
id
: "myDynamicContent",
name
: "myDynamicContent"
};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

Or add properties and values after its creation by using a dot notation:

<script type="text/javascript">

var flashvars = {};
flashvars
.name1 = "hello";
flashvars
.name2 = "world";
flashvars
.name3 = "foobar";

var params = {};
params
.menu = "false";

var attributes = {};
attributes
.id = "myDynamicContent";
attributes
.name = "myDynamicContent";

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

Which can also be written as (the less readable shorthand version for the die-hard scripter who love one-liners):

<script type="text/javascript">

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", {name1:"hello",name2:"world",name3:"foobar"}, {menu:"false"}, {id:"myDynamicContent",name:"myDynamicContent"});

</script>

If you don't want to use an optional argument you can define it as false or as an empty Object (NOTE: from SWFObject 2.1 onwards you can also use null or 0):

<script type="text/javascript">

var flashvars = false;
var params = {};
var attributes = {
id
: "myDynamicContent",
name
: "myDynamicContent"
};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

The flashvars Object is a shorthand notation that is there for your ease of use. You could potentially ignore it and specify your flashvars via the params Object:

<script type="text/javascript">

var flashvars = false;
var params = {
menu
: "false",
flashvars
: "name1=hello&name2=world&name3=foobar"
};
var attributes = {
id
: "myDynamicContent",
name
: "myDynamicContent"
};

swfobject
.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);

</script>

TIPS

SWFObject 1.5 to SWFObject 2 migration tips

  1. SWFObject 2 is NOT backwards compatible with SWFObject 1.5
  2. It is now preferred to insert all script blocks in the head of your HTML page. Adding your scripts in the body of your page may have visual impact (e.g. flashes of replaced alternative content), because your JavaScript code will be executed in a later stage (the exact impact depends on your implementation)
  3. The library itself is now written in lowercase: swfobject instead of SWFObject
  4. Methods can only be accessed via the library (instead via a SWFObject instance in SWFObject 1.5)
  5. The JavaScript API is entirely different and more elaborate
  6. SWFObject 2 replaces your entire alternative HTML content block, including the referenced HTML container element, for Flash content when enough JavaScript and Flash support is available, while SWFObject 1.5 only replaces the content inside the referenced HTML container. When you don't specify an id attribute, the object element will automatically inherit the id of the HTML container element of your alternative content.

UFO to SWFObject 2 migration tips

  1. SWFObject 2 replaces your entire alternative HTML content block, including the referenced HTML container element, for Flash content when enough JavaScript and Flash support is available, while UFO only replaces the content inside the referenced HTML container. When you don't specify an id attribute, the object element will automatically inherit the id of the HTML container element of your alternative content.
  2. UFO's setcontainercss feature has not been incorporated in SWFObject 2, however it can easily be replicated by using the SWFObject JavaScript API, see: swfobject.createCSS(selStr, declStr)

Does SWFObject 2 support MIME type application/xhtml+xml?

SWFObject 2 does NOT support XML MIME types, which is a design decision.

There are a number of reasons why we are not supporting this:

  • Only a very small (non-significant) amount of web authors is using it
  • We are unsure if it is the direction to go. Internet Explorer does not support it and all other major browser vendors are aiming their arrows at a new standard way of HTML parsing (with HTML 5), which departs from the current W3C vision of parsing HTML as XML
  • We save a considerate amount of file size and effort (testing, issue resolving) by not supporting it

Tutorials (beginner level)

Comments

The comments functionality on this wiki has been switched off to avoid spam and abuse.

If you have any questions/comments about SWFObject or its documentation, or have problems with an implementation:

  1. Please make sure you have read our FAQ
  2. Use the SWFObject discussion group

If you find any bugs or want to request a future enhancement, you can fill in an issue report on the SWFObject issues page

Posted by 1010
반응형

출처 : http://roughexistence.tistory.com/67

 

window객체의 onerror를 사용하시면 됩니다.

웹페이지에 아래 예제에서 처럼 빨간부분의 코드를 추가하시면 됩니다.

"엑세스가 거부되었습니다"도 잡힙니다.

<script type="text/javascript">
window.onerror=function(msg,file,line) {
alert("오류메세지\t"+msg+"\n"+"파일위치\t"+file+"\n"+"라인번호\t"+line);
return true; //true를 return하면 오류메세지를 발생시키지 않음
}
</script>
<script type="text/javascript">
var obj='myobj; //테스트를 위해 오류를 발생시킨 부분
</script>

다른 방법 정리
window.onerror = ErrorSetting

var e_msg="";
var e_file="";
var e_line="";

function ErrorSetting(msg, file_loc, line_no) {
e_msg=msg;
e_file=file_loc;
e_line=line_no;
return true;
}

Posted by 1010
반응형

팝업창을 닫으려고 window.close 와 self.close 를 사용하니..

창을 닫겠습니까?! 라는 경고창이 뜬다.. ㅠㅠ

사용자 왈.. 이거 안보이게 해줄수 있나요?! 흠....

겁나 검색 해보니.. 나왔다... 퍼옴...

window.open('','').close(); 이걸로 해결 했심둥...ㅋㅋ

이유는 IE 보안정책?!!!

6버전?!(아직 쓰시는분 있나?!) 과 7버전 이상의 보안정책 다르다네..

- 해결방법
IE6버전은 window.close(); 사용해도 됨(안되면 어쩔수 없구..ㅠㅠ).
IE7버전 이상은 window.open('','').close(); 이걸로...ㅎㅎ


출처 : http://jjun7983.tistory.com/141#comment10522579
Posted by 1010
반응형
ㅇ try catch문

   사용할때 : 보통 자바스크립트로 작업하다 보면 정말 어떨때는 구문에서 틀리지도 않았는데,
               브라우저 버젼에 따라 에러가 발생하기도 하고, 정말 몇달간 디버깅에 지칠때도 있다.
               대부분 열심히하면 나타나는데, 다음의 try catch문을 사용하면 편리하다.
   사용예   :
             try
             {
                  // 실제 실행시킬부분
                  var a   = opener.Location.href;
             }
             catch (e)
             {
                  // 위의 "실행시킬부분"에서 에러가 났을때 처리해줄 부분
                  alert ("opener를 찾을수 없습니다.");
             }
             finally
             {
                  // 에러가 나든 나지 않든 무조건 실행시키는 부분
                  window.status   = "opener.locatoin.href 부분 실행되었음";
             }
ㅇ typeof문
   사용할때 : 보통 데이터나 오브젝트 타입등을 검사할때 많이 사용하는데.
                만약 "undefined"이면 인식을 못한거고 "unknown"이 나올때가
                있다.. 만약 부모창에서 새창을 열고 부모창을 닫았는지 새창에서 검사할때
                if (typeof (opener) == "unknown") 이면 으로 검사할때 유용하다~ㅇ

ㅇ regExp (정규표현식)
   사용할때 : 만약 <textarea name="taContent"></textarea>에 사용자가 입력한  value값중에서
                "/아싸1/" ~ "/아싸10/" 까지를 다 "/호호1/" ~ "/호호10/" 까지로 바꿀려면 어케할까?
               
                var sTaContent   = taContent.value;
                for (var nI = 1; nI <= 10; nI++)
                {
                       var expTest = new RegExp("/아싸" + nI + "/", "ig");   // i는 대소문자 구분없고, g는 중복되어도 다처리
                       sTaContent   = sTaContent.r-place (expTest, "/호호" + nI + "/");
                }
                taContent.value   = sTaContent;
             
                하면 된다~ㅇ

                위의 expTest의 메소드들도 몇개있으므로 알아두면 많이 도움이 된다~ㅇ
                또한, 게시판의 글보기에 나오는 글들에 자동링크 걸때도 사용한다~ㅇ



ㅇ var a="08", b="09"일때
   parseInt (a)나 parseInt (b)의 값은 0 이다
   Number (a)나 Number (b)값을 해야 제대로 8과 9의 값이 나온다~ㅇ
   한번 고생한적이 있어서여~ㅇ 다른분들에게 도움이 되었으면...



ㅇ   <img name="pic1" src="">
   <img name="pic2" src="">
   <img name="pic3" src="">

   위와 같이 있고 javascript에서 pic1 ~ pic3의 src주소값을 바꾸고자 할때
   
   for (var nI = 1; nI <= 3; nI ++)
   {
        e-al("document.pic" + nI + ".src ='http://image.aaa.com/p" + nI + ".gif'");
   }
   
   위와 같이 eval을 넣어주어야 되더라구여~ㅇ



ㅇ 현재의 html파일을 다른이름을로 저장할때 뜨는 dialog박스를 열어서 저장하고 싶을때
   
   그냥 다음한줄을 실행시키면 저장 dialog박스가 뜨는걸로 뭐하는지 알겁니다~ㅇ
   document.execCommand("SaveAs", null, "a.html")

   다르게하면 다음의 한줄을 넣고
   <iframe name="ID_LOG" style="display:none"></iframe>가 body에 있다고 하고

   var sHTML = "<center>Testing...</center>";
   document.all.ID_LOG.document.close ();
   document.all.ID_LOG.document.write (sHTML);
   document.all.ID_LOG.document.execCommand("SaveAs", null, sFileName);

   하면 Testing가 찍히는 html문서를 저장할수 있져~ㅇ 그런데 이거는 IE 5.5이상에서만 됩니다.

   5.0에서는

   var sHTML   = "<input type='button' value='저장' 허용되지않은 태그 사용중=\"window.document.execCommand('SaveAs', null, 'a.html')\">";
       sHTML   += "<br><center> Testing..</center>";
   
   var oLogWin   = window.open ("", "popLog", "어쩌구...");
   
   oLogWin.document.write (sHTML);

   해서 새창띄워서 클릭하게 하면 됩니다~ㅇ



ㅇ 그리고 Javascript에서 name이나 id값이 같은것이 있으면 Array로 변하더군요...
   Javascript많이 사용하다보면 많이 접하셨을겁니다~ㅇ
   
   동적으로 name이나 id값이 1나 1이상을로 늘어날때에

   <span id="ID_A"></span>
   <span id="ID_A"></span>
   이 있다고 할때

   Javascript 안에서 에서

   var oID_A   = document.all.ID_A;

   if (typeof (oID_A [0]) != "undefined")) // 1개 이상일때
   {
   
   }
   else   // 1개만 있을경우
   {
   
   }

   물론 "ID_A" id값을 가지고 있는것이 있는지 먼저 검사하면 좋져~ㅇ



ㅇ 만약 a와 b와 c의 값을 구분자 ","로 구분하는 String (a,b,c)을 만들고 싶을때

   var oTmpArray = new Array ("a", "b", "c");
   var sValue = oTmpArray.j-in (",");



ㅇ javascript 연관배열
   
   var oMethod =   {
        "ALERT"   : goAlert,
        "MSG"   : goMsg
   }

   oMethod ["ALERT"] 는
   goAlert가 됩니다.



ㅇ 허용되지않은 태그 사허용되지않은 태그 사용중그 사용중, onMousewheel... 등등의 이벤트를 붙이거나 떼기
   
   window.attachEvent ("onscroll", procScroll);
    하면 onscroll이벤트 발생시 procScroll함수 실행
   
   window.detachEvent ("onscroll", procScroll);
   하면 onscroll이벤트 떼기



ㅇ 움직이는 gif이미지를 key이벤트나 등등 이벤트사용하면 움직이던 gif이미지가 멈추어버립니다.
   알고보니 return값땜시 "event.returnValue = 'false'" 해주면 되더라구여~ㅇ



ㅇ ActiveX를 사용시 ActiveX클라이언트가 ActiveX를 다운 받았는지 확인할때는
   
   <object name=AX1 id=AX1></object> 가 있을때

   var bnResult   = typeof (AX1.proc) == "unknown")? true : false;
   proc는 AX1의 method입니다~ㅇ
   이렇게 확인하면 되더라구여~ㅇ



ㅇ F5번 누를때 경고창(confirm같은것)띄워서 새로고침 할건지 물어보기
   
   window.onbeforeunload   = hoho ();

   function hoho ()
   {
        var sMsg = "새로고침을 정말로 정말로 정말로 할꺼예여?";
        return (sMsg);
   }
   물론 F5번 눌렀을때를 key Event로 잡아서 함수안에서 실행해도 됩니다~ㅇ



ㅇ VBscript에만 있는줄 알았던 with 많이 쓰일때가 있더군요 switch문을 안에다가 사용하면 정말 깔끔!
   
   with (window)
   {
           = pageOnLoad;
        o-unload = pageUnload;
   }

Posted by 1010
반응형

/**********************************************************************
 *
 *  cookie 공통 모듈
 *
 **********************************************************************/
/**
  * 쿠키정보 가져오기
  * @param name  쿠키명
  */
function getCookie(name) {
 var Found = false;
 var start, end;
 var i = 0;
 var cookieData = document.cookie;
 while(i <= cookieData.length) {
    start = i;
   end = start + name.length;
   
   if(cookieData.substring(start, end) == name) {
      Found = true;
      break;
    }
    i++;
 }
 if(Found == true) {
    start = end + 1;
    end = cookieData.indexOf(";", start);
    if(end < start)
      end = cookieData.length;
     return cookieData.substring(start, end);
   }
    
 return "";
}

/**
  * 쿠키 설정
  * @param cookieName 쿠키명
  * @param cookieValue 쿠키값
  * @param expireDay 쿠키 유효날짜
  */
function setCookie( cookieName, cookieValue){
   var today = new Date();
   today.setDate( today.getDate() + 365 );   // 저장 기간
   document.cookie = cookieName + "=" +  cookieValue  + "; path=/; expires=" + today.toGMTString() + ";";
}

/**
  * 쿠키 삭제
  * @param cookieName 삭제할 쿠키명
  */
function deleteCookie(cookieName ){
   var expireDate = new Date();
 
   //어제 날짜를 쿠키 소멸 날짜로 설정한다.
   expireDate.setDate( expireDate.getDate() - 1 );
   document.cookie = cookieName + "=" + "; expires=" + expireDate.toGMTString() + "; path=/";
 
}

/**********************************************************************
 *
 *  관심자료 cookie
 *
 **********************************************************************/

/**
  * 관심자료 목록 가져오기
  * return : list1[]
  */
function getCernDatList(){
 var list =  "";
 if (navigator.appName.charAt(0) == 'N') {
  list = fromUtf8(getCookie('cernDatList'));
 } else if (navigator.appName.charAt(0) == 'M') {
  list = getCookie('cernDatList');
 }
 if(list.length>0){
  list =  list.split("---");
 }else{
  list = "";
 }
 return list;
}


/**
  * 관심자료 등록 
  */
function setCernDatList(url,title){
 if(title!=""){
  //1.관심자료 목록 가져오기
  var datList = getCernDatList();
  var tempData = "";
  var mode = 0;
  var first = 0;
  var uName = "";
  if(datList.length>0){
   //2. 중복자료 검사
   var para = "";
   var titleV = "";
   var temp = "";
   for(var i=0;i<datList.length;i++){
    temp = datList[i].split("--");
    if(temp != null){
     para = temp[0].substring(4);
     titleV = temp[1].substring(6);
     if(para==url){
      mode = 1;
      break;
     }else{
      // 2-1 데이터 저장
      if(tempData==""){
        uName = 'url=';
      }else{
        uName = '---url=';
      }
      if (navigator.appName.charAt(0) == 'N') {
       tempData += uName+toUtf8(para)+'--title='+toUtf8(titleV);
      } else if (navigator.appName.charAt(0) == 'M') {
       tempData += uName+para+'--title='+titleV;
      }
     }
    }
   }
  }else{
   first = 1;
  }
  //3. 등록 
  if(mode == 0){
   if(datList.length <= 20){    // 저장 개수 설정
    if(first==1){
     uName = 'url=';
    }else{
     uName = tempData+'---url=';
    }
    if (navigator.appName.charAt(0) == 'N') {
     setCookie('cernDatList',uName+toUtf8(url)+'--title='+toUtf8(title));
    } else if (navigator.appName.charAt(0) == 'M') {
     setCookie('cernDatList',uName+url+'--title='+title);
    }
   
    //4. 등록 확인
    var resultSize = getCernDatList();
    if(datList.length<resultSize.length){
     alert("관심자료에 등록되었습니다.");
    }else{
     alert("관심자료 등록 중 오류가 발생하였습니다.");
    }
   }else{
    alert("저장 개수가 초과되었습니다.\n(20개까지 저장 가능합니다.)");
   }
  }else{
   alert("이미 등록된 자료입니다.");
  } 
 }else{
  alert("등록 자료가 없습니다.");
 }
}

/**
  * 관심자료 삭제
  */
function delCernDatList(){
 var oldCernSize = getCernDatList();
 //if(!document.cernFrm.allCernLi.checked){
  
  var delNo = "";
  var cernList = "";
  var temp = "";
  var para = "";
  var titleV = "";
  var tempData = "";
  var boo = "";
  var cntCheckNo = 0;
  for(var i=0;i<els("cernLi").length;i++){
   if(els("cernLi").length==1){
    boo = els("cernLi")[i].checked
    delNo = els("cernLi")[i].value;
    
   }else{
    boo = els("cernLi")[i].checked
    delNo = els("cernLi")[i].value;
   }
    cernList = getCernDatList();
    tempData = "";
   if(getCookie('cernDatList')!=""){
    for(var j=0;j<cernList.length;j++){
     temp = cernList[j].split("--");
     para = temp[0].substring(4);
     titleV = temp[1].substring(6);
     if(para==delNo && boo==true){
      cntCheckNo = 1;
     }else{
      if(tempData==""){
        uName = 'url=';
      }else{
        uName = '---url=';
      }
      if (navigator.appName.charAt(0) == 'N') {
       tempData += uName+toUtf8(para)+'--title='+toUtf8(titleV);
      } else if (navigator.appName.charAt(0) == 'M') {
       tempData += uName+para+'--title='+titleV;
      }
     }
    }
    // 삭제 리스트 제외한 리스트 저장
    setCookie('cernDatList',tempData);
   }
  }
  if(cntCheckNo>0){
   //setCookie('cernDatList',tempData);
   var afList = getCernDatList();
   if(oldCernSize.length>afList.length){
    alert("관심자료 삭제 성공");
   }else{
    alert("관심자료 삭제 실패");
   }
  }else{
   alert("선택된 자료가 없습니다.");
  }
 outputList();
}


/**
  * 관심자료 리스트 뿌려주기
  */
function outputList() {
    var temp = "";
 if (navigator.appName.charAt(0) == 'N') {
     temp = fromUtf8(getCookie('cernDatList'));
   } else if (navigator.appName.charAt(0) == 'M') {
     temp = getCookie('cernDatList');
   }
 var text = temp.split("---");
 var outText = "";
 var divHtml = "<ul>";
 if(temp!=""){
  var sortNo = text.length-1;
  var tempNo = 0;
  for(var i = 0; i<text.length;i++){
    outText = text[sortNo].split("--");
    tempNo = i+1;
    divHtml += "<li><input type=\"checkbox\" class=\"vmid\" name=\"cernLi\" value=\""+outText[0].substring(4)+"\"/><a href=\"#\" onclick=\"javascript:openPop('"
      + outText[0].substring(4) + "');\">&nbsp;" + tempNo +".&nbsp;"
      + outText[1].substring(6).replace("00000","<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;") +
      "</a></li>";
    sortNo--;
     }
 }else{
   divHtml += "<li>자료 없음</li>";
 }
 //alert(divHtml);
    document.getElementById("cernDat").innerHTML = divHtml+"</ul>";

 
/**
  * 관심자료 리스트 보여주기
  */
function fCernDat(){
 var mode = document.getElementById("cernDat").style.display;
 if(mode==""){
  document.getElementById("cernDat").style.display = "none";
 }else{
  document.getElementById("cernDat").style.display = "";
  outputList();
 }
 
   
}
 
/**********************************************************************
 *
 *  Unicode ⇔ UTF-8
 *
 **********************************************************************/

function toUtf8(s) {
  var c, d = "";
  for (var i = 0; i < s.length; i++) {
    c = s.charCodeAt(i);
    if (c <= 0x7f) {
      d += s.charAt(i);
    } else if (c >= 0x80 && c <= 0x7ff) {
      d += String.fromCharCode(((c >> 6) & 0x1f) | 0xc0);
      d += String.fromCharCode((c & 0x3f) | 0x80);
    } else {
      d += String.fromCharCode((c >> 12) | 0xe0);
      d += String.fromCharCode(((c >> 6) & 0x3f) | 0x80);
      d += String.fromCharCode((c & 0x3f) | 0x80);
    }
  }
  return d;
}

function fromUtf8(s) {
  var c, d = "", flag = 0, tmp;
  for (var i = 0; i < s.length; i++) {
    c = s.charCodeAt(i);
    if (flag == 0) {
      if ((c & 0xe0) == 0xe0) {
        flag = 2;
        tmp = (c & 0x0f) << 12;
      } else if ((c & 0xc0) == 0xc0) {
        flag = 1;
        tmp = (c & 0x1f) << 6;
      } else if ((c & 0x80) == 0) {
        d += s.charAt(i);
      } else {
        flag = 0;
      }
    } else if (flag == 1) {
      flag = 0;
      d += String.fromCharCode(tmp | (c & 0x3f));
    } else if (flag == 2) {
      flag = 3;
      tmp |= (c & 0x3f) << 6;
    } else if (flag == 3) {
      flag = 0;
      d += String.fromCharCode(tmp | (c & 0x3f));
    } else {
      flag = 0;
    }
  }
  return d;
}

 /**********************************************************************
 *
 *  내가 찾은 자료  & 검색어 목록
 *
 **********************************************************************/
 
/**
  * 리스트 보여주기
  */
function fQuickDat(dataId){
 var mode = document.getElementById(dataId+"List").style.display;
 if(mode==""){
  document.getElementById(dataId+"List").style.display = "none";
 }else{
  document.getElementById(dataId+"List").style.display = "";
  outputDataList(dataId);
 }
 
   
}
 
 
/**
  * 목록 가져오기
  * return : list1[]
  */
function getDatList(dataId){
 var list =  "";
 if (navigator.appName.charAt(0) == 'N') {
  list = fromUtf8(getCookie(dataId));
 } else if (navigator.appName.charAt(0) == 'M') {
  list = getCookie(dataId);
 }
 if(list.length>0){
  list =  list.split("---");
 }else{
  list = "";
 }
 return list;
}

/**
  * 등록 
  */
function setDatList(dataId, url, title){
 
 if(title != ""){
  //1.목록 가져오기
  var datList = getDatList(dataId);
  var tempData = "";
  var first = 0;
  var uName = "";
  if(datList.length > 0){
   //2. 중복자료 검사
   var preSavedUrl = "";
   var preSavedTitle = "";
   var temp = "";
  
   for(var i = 0; i < datList.length; i++){
    temp = datList[i].split("--");
    preSavedUrl = temp[0].substring(4);
    preSavedTitle = temp[1].substring(6);
   
    if(preSavedUrl == url){
     //alert(preSavedUrl); 최상위로 올림
     //return false;
     
    }else{
     // 2-1 데이터 저장
     if(tempData == ""){
       uName = 'url=';
     }else{
       uName = '---url=';
     }
     if (navigator.appName.charAt(0) == 'N') {
      tempData += uName + toUtf8(preSavedUrl) + '--title=' + toUtf8(preSavedTitle);
     } else if (navigator.appName.charAt(0) == 'M') {
      tempData += uName + preSavedUrl + '--title=' + preSavedTitle;
     }
    }
   }
  }
  else{
   first = 1;
  }
  
  //3. 등록 
  //alert(mode+"---"+datList.length);
  if(first==1){
   uName = 'url=';
  }
  else{
   uName = tempData + '---url=';
  }
 
  if (navigator.appName.charAt(0) == 'N') {
   setCookie(dataId, uName + toUtf8(url) + '--title=' + toUtf8(title));
  }
  else if (navigator.appName.charAt(0) == 'M') {
   setCookie(dataId, uName + url + '--title=' + title);
  }
 
  //alert(datList.length);
  if(datList.length > 20){  // 저장 개수 설정
   delDatList(dataId, 1);
  }
 }
 
}

 
 
/**
  * 삭제        (쿠키 id, 삭제 모드)
  */
function delDatList(dataId,mode){
 var oldCernSize = getDatList(dataId);
 if(mode==1){
  var cernList = "";
  var temp = "";
  var para = "";
  var titleV = "";
  var tempData = "";
 
    cernList = getDatList(dataId);
    tempData = "";
   if(getCookie(dataId)!=""){
    for(var j=0;j<cernList.length;j++){
     temp = cernList[j].split("--");
     para = temp[0].substring(4);
     titleV = temp[1].substring(6);
     if(j==0){
      
     }else{
      if(tempData==""){
        uName = 'url=';
      }else{
        uName = '---url=';
      }
      if (navigator.appName.charAt(0) == 'N') {
       tempData += uName+toUtf8(para)+'--title='+toUtf8(titleV);
      } else if (navigator.appName.charAt(0) == 'M') {
       tempData += uName+para+'--title='+titleV;
      }
     }
    }
    // 삭제 리스트 제외한 리스트 저장
    setCookie(dataId,tempData);
   }
  
 }else{
  deleteCookie(dataId);
  var resultSize = getDatList(dataId);
  if(oldCernSize.length>resultSize.length){
   alert("삭제 성공");
  }else{
   alert("삭제 실패");
  }
 }
 //outputDataList(dataId);
}
 
 
/**
  * 리스트 뿌려주기
  */
function outputDataList(dataId) {
    var temp = "";
 if (navigator.appName.charAt(0) == 'N') {
     temp = fromUtf8(getCookie(dataId));
   } else if (navigator.appName.charAt(0) == 'M') {
     temp = getCookie(dataId);
   }
 var text = temp.split("---");
 var outText = "";
 var divHtml = "";
 var conTit = "";
 if(temp!=""){
  var sortNo = text.length-1;
  for(var i = 0; i < text.length && i < mainListSize;i++){
    outText = text[sortNo].split("--");
   if(outText != ""){
    if(dataId=="myFindDat"){
     idxStart = outText[1].indexOf("[");
   
     if(idxStart > 6) subject = outText[1].substring(6, idxStart);
     else    subject = outText[1].substring(6);
     subject = subject.replace("00000","").replace("_", "").replace("title=", "").replace("n", "");
     if(subject.length > 23) subject = subject.substring(0, 24) + "...";
     
     if(idxStart > 0){
         content = outText[1].substring(idxStart);
         conTit  = outText[1].substring(idxStart);
        
     } else {
         content = "";
         conTit  = "";
     }
     
     if(content.length > 8) content = content.substring(0, 9) + "...";
   
     divHtml += "<dt><a href=\"#\" onclick=\"javascript:openPop('" + outText[0].substring(4) + "');\" >"
      //+ (i + 1) + ". "
      + subject + "</a></dt>";    
     divHtml += "<dd><span title='"+conTit+"'>" + content + "</span></dd><br>";
    }else{
     divHtml += "<p><a href=\"#\" onclick=\"javascript:openPop('" + outText[0].substring(4) + "');\" >"
      + (i + 1) + ". " + outText[1].substring(6) + "</a></p><br>";
    }
   }
    sortNo--;
     }
         /*alert(outText[0].substring(4));
         alert(outText[1].substring(6));*/
 }else{
   divHtml += "<dt>조회한 이력이 없습니다.</dt>";
 }
    document.getElementById(dataId).innerHTML = "<dl>" + divHtml + "</dl>";

function outputDataNmList(dataId) {

    var temp = "";
 if (navigator.appName.charAt(0) == 'N') {
     temp = fromUtf8(getCookie(dataId));
   } else if (navigator.appName.charAt(0) == 'M') {
     temp = getCookie(dataId);
   }
 var text = temp.split("---");
 var outText = "";
 var divHtml = "";
 if(temp!=""){
  var sortNo = text.length-1;
  for(var i = 0; i < text.length;i++){
    outText = text[sortNo].split("--");
    divHtml += "<p><a href=" + outText[0].substring(4) + " >"
      + (i + 1) + ". " + outText[1].substring(6) + "</a></p>";
    sortNo--;
     }
         /*alert(outText[0].substring(4));
         alert(outText[1].substring(6));*/
 }else{
   divHtml += "<p>자료 없음</p>";
 }
    document.getElementById(dataId).innerHTML = divHtml;


/**
  * 검색어 쿠키 등록
  */
function fSearchKeySaveF(){
 setDatList('schTrmDat','searchKeyWord',document.getElementById("searchKeyWord").value);
}

function searchTrmSave(url, id){
 setDatList('schTrmDat', url, el(id).value);
}

/**
  * 검색어 쿠키 등록  (다음 실행 함수)
  */
function fSearchKeySave(nextProc){
 setDatList('schTrmDat','searchKeyWord',document.getElementById("searchKeyWord").value);
 nextProc();
}

function addMyFindDat(url, id){
    try{
 url = url.replaceAll("<strong>", "").replaceAll("</strong>", "");
 setDatList("myFindDat", url, id)
 }catch(e){deleteCookie("myFindDat");}
}

// 내가 찾은용어  검색 라인에 보여주기
function searchTrmView(callBackName){
 var temp = "";
 var dataId = "schTrmDat";
 if (navigator.appName.charAt(0) == 'N') {
     temp = fromUtf8(getCookie(dataId));
   } else if (navigator.appName.charAt(0) == 'M') {
     temp = getCookie(dataId);
   }
 var text = temp.split("---");
 var outText = "";
 var divHtml = "";
 if(temp == null || temp.trim() == ""){
   divHtml += "검색어를 입력하세요.";
 }
 else{
  var sortNo = text.length;
  if(sortNo > 5){
   sortNo = 5;
  }
  var tempNo = text.length - 1;
  var txtTitle = "";
  for(var i = 0; i < sortNo; i++){
    outText = text[tempNo].split("--");
    txtTitle = outText[1].substring(6);
    if(txtTitle.length > 7){
     txtTitle = txtTitle.substring(0,7) + "...";
    }

   if(i > 0) divHtml += ", ";
   if(typeof(callBackName) != "undefined" && callBackName != null){
    divHtml += "<a href=# onclick=\"javascript:" + callBackName + "('" + outText[1].substring(6) + "');\" >" + txtTitle + "</a>";
   }
   else{
     divHtml += "<a href=" + outText[0].substring(4) + " title="+outText[1].substring(6)+">" + txtTitle + "</a>";
   }

    tempNo --;
     }
  divHtml = divHtml.substring(0, divHtml.length - 1); 
 }

    document.getElementById("searchTrm").innerHTML = divHtml;
}


 /**********************************************************************
 *
 *  내가 찾은 법령 이력
 *
 **********************************************************************/
var maxDetailCookie = 10;
function setDetailSelectCookie(lawKubun,seq){
 var dataId = "lawHistory";
 var dataSeq = "";
 var dataSeq = lawKubun+","+seq;
 
 if(dataSeq != ""){
  var datList = getDatList(dataId);
  var tempData = "";
  var uName = "";
  var isFirst = true;
  if(datList.length > 0){
   for(var i = 0; i < datList.length; i++){
    if ( datList[i] == dataSeq ) continue;

    if(tempData == ""){
      uName = "";
    }else{
      uName = "---";
    }
    if (navigator.appName.charAt(0) == 'N') {
     tempData += uName + toUtf8(datList[i]);
    } else if (navigator.appName.charAt(0) == 'M') {
     tempData += uName + datList[i];
    }       
   }
   isFirst = false;
  }
 
  if( isFirst == true ) {
   uName = "";
  } else {
   uName = tempData + "---";
  }
 
  if (navigator.appName.charAt(0) == 'N') {
   setCookie(dataId, uName + toUtf8(dataSeq));
  } else if (navigator.appName.charAt(0) == 'M') {
   setCookie(dataId, uName + dataSeq);
  } 
 
  if(datList.length >= maxDetailCookie){  // 저장 개수 설정
   delDetailSelectCookie(dataId);
  }     
 }
}

/**
  * 20개 이상 쿠키 삭제
  */
function delDetailSelectCookie(dataId){
 var oldList = getDatList(dataId);
 
 if ( oldList.length <= maxDetailCookie ) return;
 
 var tmpData = "";
 var isFirst = true;
 var uName = "";
 
 
 oldList.reverse();
 
 for(var i = 0; i < maxDetailCookie; i ++) {
  if ( i == 0 )
   uName = "";
  else
   uName = "---";
  if (navigator.appName.charAt(0) == 'N') {
   tmpData = toUtf8(oldList[i]) + uName + tmpData;
  } else if (navigator.appName.charAt(0) == 'M') {
   tmpData = oldList[i] + uName + tmpData;
  }
 }
 
 // 삭제 리스트 제외한 리스트 저장
 setCookie(dataId,tmpData);
}

function getDetailSelectCookie(dataId){
 var list =  "";
 if (navigator.appName.charAt(0) == 'N') {
  list = fromUtf8(getCookie(dataId));
 } else if (navigator.appName.charAt(0) == 'M') {
  list = getCookie(dataId);
 }
 return list;
}



/**********************************************************************
 *
 *  Nethru_pcId 모듈
 *
 **********************************************************************/

function Nethru_getCookieVal(offset)
{
 var endstr = document.cookie.indexOf (";", offset);
 if (endstr == -1)
  endstr = document.cookie.length;
 return unescape(document.cookie.substring(offset, endstr));
}

function Nethru_SetCookie(name, value){
   var argv = Nethru_SetCookie.arguments;
   var argc = Nethru_SetCookie.arguments.length;
   var expires = (2 < argc) ? argv[2] : null;
   var path = (3 < argc) ? argv[3] : null;
   var domain = (4 < argc) ? argv[4] : null;
   var secure = (5 < argc) ? argv[5] : false;
 //alert(value);
   //alert("DOMAIN = " + domain);
   document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires="+expires.toGMTString())) +
     ((path == null) ? "" : ("; path=" + path)) +
     ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");

 //alert(document.cookie);
}

function Nethru_GetCookie(name){
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen)
      {
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg)
         return Nethru_getCookieVal (j);
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0)
         break;
      }
  return null;
}

function Nethru_makePersistentCookie(name,length,path,domain)
{
// alert(name+" -- "+length+"--"+path+"--"+domain);
    var today = new Date();
    var expiredDate = new Date(2011,1,1);
    var cookie;
 var value;

    cookie = Nethru_GetCookie(name);
    if ( cookie ) {
//  alert(cookie);
        return 1;
 }

 var values = new Array();
 for ( i=0; i < length ; i++ ) {
  values[i] = "" + Math.random();
 }

 value = today.getTime();

 // use first decimal
 for ( i=0; i < length ; i++ ) {
  value += values[i].charAt(2);
 }

    Nethru_SetCookie(name,value,expiredDate,path,domain);
}

function Nethru_getDomain() {
 var _host   = document.domain;
 var so      = _host.split('.');
 var dm    = so[so.length-2] + '.' + so[so.length-1];
 return (so[so.length-1].length == 2) ? so[so.length-3] + '.' + dm : dm;
}

var Nethru_domain  = Nethru_getDomain();
Nethru_makePersistentCookie("PCID",10,"/",Nethru_domain);



Posted by 1010
반응형

/// #############################################################################
/// #####
/// ##### 한국신용정보주식회사 서비스 운영에 필요한 Crypto JavaScript 소스
/// #####
/// ##### =====================================================================
/// #####
/// ##### Descriptions
/// #####  - 서비스 운영에 필요한 Javascript Crypto Algorithm을 관리한다.
/// #####
/// ##### ---------------------------------------------------------------------
/// #####
/// ##### 작성자   : (주)유비아이에스컨설팅 (www.ubisc.com)
/// ##### 원본참조 :
/// ##### 원본파일 :
/// ##### 작성일자 : 2006.02.06
/// #####
/// #############################################################################

// -----------------------------------------------------
// ----- 보안 처리를 위한 Object 처리 정보
// -----------------------------------------------------

var cryptoObject = new Object();
cryptoObject.KeyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

//
// Base 64 Decode
//
cryptoObject.decode64 = function( input )
{
 var output = "";
 var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    var strValue = input;

    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
 var re = /[^A-Za-z0-9\+\/\=]/g;
    strValue = strValue.replace( re, "" );

    do
    {
       enc1 = cryptoObject.KeyStr.indexOf(strValue.charAt(i++));
       enc2 = cryptoObject.KeyStr.indexOf(strValue.charAt(i++));
       enc3 = cryptoObject.KeyStr.indexOf(strValue.charAt(i++));
       enc4 = cryptoObject.KeyStr.indexOf(strValue.charAt(i++));

       chr1 = (enc1 << 2) | (enc2 >> 4);
       chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
       chr3 = ((enc3 & 3) << 6) | enc4;

       output = output + String.fromCharCode(chr1);

       if (enc3 != 64)
       {
          output = output + String.fromCharCode(chr2);
       }

       if (enc4 != 64)
       {
          output = output + String.fromCharCode(chr3);
       }
    }
    while (i < strValue.length);

   return output;
}

//
// Base 64 Encode
//
cryptoObject.encode64 = function( input )
{
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    do
    {
       chr1 = input.charCodeAt(i++);
       chr2 = input.charCodeAt(i++);
       chr3 = input.charCodeAt(i++);

       enc1 = chr1 >> 2;
       enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
       enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
       enc4 = chr3 & 63;

       if (isNaN(chr2))
       {
         enc3 = enc4 = 64;
       }
       else if (isNaN(chr3))
       {
        enc4 = 64;
       }

       output = output + cryptoObject.KeyStr.charAt(enc1) + cryptoObject.KeyStr.charAt(enc2) +
          cryptoObject.KeyStr.charAt(enc3) + cryptoObject.KeyStr.charAt(enc4);
    }
    while (i < input.length);

    return output;
}

//
// MD5 Hash
//
cryptoObject.md5 = function( sMessage )
{
  function RotateLeft(lValue, iShiftBits) { return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits)); }
  function AddUnsigned(lX,lY) {
  var lX4,lY4,lX8,lY8,lResult;
  lX8 = (lX & 0x80000000);
  lY8 = (lY & 0x80000000);
  lX4 = (lX & 0x40000000);
  lY4 = (lY & 0x40000000);
  lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
  if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
  if (lX4 | lY4)
  {
   if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
   else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
  }
  else return (lResult ^ lX8 ^ lY8);
 }
 function F(x,y,z) { return (x & y) | ((~x) & z); }
 function G(x,y,z) { return (x & z) | (y & (~z)); }
 function H(x,y,z) { return (x ^ y ^ z); }
 function I(x,y,z) { return (y ^ (x | (~z))); }
 function FF(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 }
 function GG(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 }
 function HH(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 }
 function II(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 }
 function ConvertToWordArray(sMessage)
 {
  var strMsg = new String( sMessage );
  var lWordCount;
  var lMessageLength = strMsg.length;
  var lNumberOfWords_temp1=lMessageLength + 8;
  var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
  var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
  var lWordArray=Array(lNumberOfWords-1);
  var lBytePosition = 0;
  var lByteCount = 0;
  while ( lByteCount < lMessageLength ) {
   lWordCount = (lByteCount-(lByteCount % 4))/4;
   lBytePosition = (lByteCount % 4)*8;
   lWordArray[lWordCount] = (lWordArray[lWordCount] | (strMsg.charCodeAt(lByteCount)<<lBytePosition));
   lByteCount++;
  }
  lWordCount = (lByteCount-(lByteCount % 4))/4;
  lBytePosition = (lByteCount % 4)*8;
  lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
  lWordArray[lNumberOfWords-2] = lMessageLength<<3;
  lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
  return lWordArray;
 }
 function WordToHex(lValue) {
  var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
  for (lCount = 0;lCount<=3;lCount++) {
   lByte = (lValue>>>(lCount*8)) & 255;
   WordToHexValue_temp = "0" + lByte.toString(16);
   WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
  }
  return WordToHexValue;
 }

 var strMsg = new String( sMessage );
 var x=Array();
 var k,AA,BB,CC,DD,a,b,c,d
 var S11=7, S12=12, S13=17, S14=22;
 var S21=5, S22=9 , S23=14, S24=20;
 var S31=4, S32=11, S33=16, S34=23;
 var S41=6, S42=10, S43=15, S44=21;
 // Steps 1 and 2.  Append padding bits and length and convert to words
 x = ConvertToWordArray(strMsg);
 // Step 3.  Initialise
 a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 // Step 4.  Process the message in 16-word blocks
 for (k=0;k<x.length;k+=16) {
  AA=a; BB=b; CC=c; DD=d;
  a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
  d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
  c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
  b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
  a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
  d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
  c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
  b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
  a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
  d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
  c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
  b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
  a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
  d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
  c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
  b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
  a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
  d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
  c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
  b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
  a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
  d=GG(d,a,b,c,x[k+10],S22,0x2441453);
  c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
  b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
  a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
  d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
  c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
  b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
  a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
  d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
  c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
  b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
  a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
  d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
  c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
  b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
  a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
  d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
  c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
  b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
  a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
  d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
  c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
  b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
  a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
  d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
  c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
  b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
  a=II(a,b,c,d,x[k+0], S41,0xF4292244);
  d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
  c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
  b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
  a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
  d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
  c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
  b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
  a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
  d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
  c=II(c,d,a,b,x[k+6], S43,0xA3014314);
  b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
  a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
  d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
  c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
  b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
  a=AddUnsigned(a,AA); b=AddUnsigned(b,BB); c=AddUnsigned(c,CC); d=AddUnsigned(d,DD);
 }
 // Step 5.  Output the 128 bit digest
 var temp= WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 return temp.toLowerCase();
}

//
// DES Symmetric Key
//
cryptoObject.des = function( key, message, encrypt, mode, iv )
{
 //des_createKeys
 //this takes as input a 64 bit key (even though only 56 bits are used)
 //as an array of 2 integers, and returns 16 48 bit keys
 function des_createKeys( key )
 {
  //declaring this locally speeds things up a bit
    pc2bytes0  = new Array (0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204);
    pc2bytes1  = new Array (0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101);
    pc2bytes2  = new Array (0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808);
    pc2bytes3  = new Array (0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000);
    pc2bytes4  = new Array (0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010);
    pc2bytes5  = new Array (0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420);
    pc2bytes6  = new Array (0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002);
    pc2bytes7  = new Array (0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800);
    pc2bytes8  = new Array (0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002);
    pc2bytes9  = new Array (0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408);
    pc2bytes10 = new Array (0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020);
    pc2bytes11 = new Array (0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200);
    pc2bytes12 = new Array (0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010);
    pc2bytes13 = new Array (0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105);

    //how many iterations (1 for des, 3 for triple des)
    var iterations = key.length >= 24 ? 3 : 1;
    //stores the return keys
    var keys = new Array (32 * iterations);
    //now define the left shifts which need to be done
    var shifts = new Array (0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0);
    //other variables
    var lefttemp, righttemp, m=0, n=0, temp;

    for (var j=0; j<iterations; j++)
    { //either 1 or 3 iterations
     left = (key.charCodeAt(m++) << 24) | (key.charCodeAt(m++) << 16) | (key.charCodeAt(m++) << 8) | key.charCodeAt(m++);
       right = (key.charCodeAt(m++) << 24) | (key.charCodeAt(m++) << 16) | (key.charCodeAt(m++) << 8) | key.charCodeAt(m++);

       temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
       temp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= temp; right ^= (temp << -16);
       temp = ((left >>> 2) ^ right) & 0x33333333; right ^= temp; left ^= (temp << 2);
       temp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= temp; right ^= (temp << -16);
       temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
       temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
       temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);

       //the right side needs to be shifted and to get the last four bits of the left side
       temp = (left << 8) | ((right >>> 20) & 0x000000f0);
       //left needs to be put upside down
       left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
       right = temp;

       //now go through and perform these shifts on the left and right keys
       for (i=0; i < shifts.length; i++)
       {
         //shift the keys either one or two bits to the left
         if (shifts[i]) {left = (left << 2) | (left >>> 26); right = (right << 2) | (right >>> 26);}
         else {left = (left << 1) | (left >>> 27); right = (right << 1) | (right >>> 27);}
         left &= 0xfffffff0; right &= 0xfffffff0;

         //now apply PC-2, in such a way that E is easier when encrypting or decrypting
         //this conversion will look like PC-2 except only the last 6 bits of each byte are used
         //rather than 48 consecutive bits and the order of lines will be according to
         //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
         lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf]
                 | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf]
                 | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf]
                 | pc2bytes6[(left >>> 4) & 0xf];
         righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf]
                   | pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf]
                   | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf]
                   | pc2bytes13[(right >>> 4) & 0xf];
         temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
         keys[n++] = lefttemp ^ temp; keys[n++] = righttemp ^ (temp << 16);
       }
    } //for each iterations

    //return the keys we've created
    return keys;
 } //end of des_createKeys

 //declaring this locally speeds things up a bit
   var spfunction1 = new Array (0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004);
   var spfunction2 = new Array (0x80108020,0x80008000,0x8000,0x108020,0x100000,0x20,0x80100020,0x80008020,0x80000020,0x80108020,0x80108000,0x80000000,0x80008000,0x100000,0x20,0x80100020,0x108000,0x100020,0x80008020,0,0x80000000,0x8000,0x108020,0x80100000,0x100020,0x80000020,0,0x108000,0x8020,0x80108000,0x80100000,0x8020,0,0x108020,0x80100020,0x100000,0x80008020,0x80100000,0x80108000,0x8000,0x80100000,0x80008000,0x20,0x80108020,0x108020,0x20,0x8000,0x80000000,0x8020,0x80108000,0x100000,0x80000020,0x100020,0x80008020,0x80000020,0x100020,0x108000,0,0x80008000,0x8020,0x80000000,0x80100020,0x80108020,0x108000);
   var spfunction3 = new Array (0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200);
   var spfunction4 = new Array (0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080);
   var spfunction5 = new Array (0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100);
   var spfunction6 = new Array (0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010);
   var spfunction7 = new Array (0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002);
   var spfunction8 = new Array (0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000);

   //create the 16 or 48 subkeys we will need
   var keys = des_createKeys (key);
   var m=0, i, j, temp, temp2, right1, right2, left, right, looping;
   var cbcleft, cbcleft2, cbcright, cbcright2
   var endloop, loopinc;
   var len = message.length;
   var chunk = 0;
   //set up the loops for single and triple des
   var iterations = keys.length == 32 ? 3 : 9; //single or triple des
   if (iterations == 3) {looping = encrypt ? new Array (0, 32, 2) : new Array (30, -2, -2);}
   else {looping = encrypt ? new Array (0, 32, 2, 62, 30, -2, 64, 96, 2) : new Array (94, 62, -2, 32, 64, 2, 30, -2, -2);}

   message += "\0\0\0\0\0\0\0\0"; //pad the message out with null bytes
   //store the result here
   result = "";
   tempresult = "";

   if (mode == 1) { //CBC mode
     cbcleft = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);
     cbcright = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);
     m=0;
   }

   //loop through each 64 bit chunk of the message
   while (m < len)
   {
     left = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);
     right = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);

     //for Cipher Block Chaining mode, xor the message with the previous result
     if (mode == 1) {if (encrypt) {left ^= cbcleft; right ^= cbcright;} else {cbcleft2 = cbcleft; cbcright2 = cbcright; cbcleft = left; cbcright = right;}}

     //first each 64 but chunk of the message must be permuted according to IP
     temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
     temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);
     temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);
     temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
     temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);

     left = ((left << 1) | (left >>> 31));
     right = ((right << 1) | (right >>> 31));

     //do this either 1 or 3 times for each chunk of the message
     for (j=0; j<iterations; j+=3)
     {
        endloop = looping[j+1];
        loopinc = looping[j+2];
        //now go through and perform the encryption or decryption
        for (i=looping[j]; i!=endloop; i+=loopinc)
        { //for efficiency
          right1 = right ^ keys[i];
          right2 = ((right >>> 4) | (right << 28)) ^ keys[i+1];
          //the result is attained by passing these bytes through the S selection functions
          temp = left;
          left = right;
          right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f]
                | spfunction6[(right1 >>>  8) & 0x3f] | spfunction8[right1 & 0x3f]
                | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & 0x3f]
                | spfunction5[(right2 >>>  8) & 0x3f] | spfunction7[right2 & 0x3f]);
        }

        temp = left; left = right; right = temp; //unreverse left and right
     } //for either 1 or 3 iterations

     //move then each one bit to the right
     left = ((left >>> 1) | (left << 31));
     right = ((right >>> 1) | (right << 31));

     //now perform IP-1, which is IP in the opposite direction
     temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
     temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
     temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);
     temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);
     temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);

     //for Cipher Block Chaining mode, xor the message with the previous result
     if (mode == 1) {if (encrypt) {cbcleft = left; cbcright = right;} else {left ^= cbcleft2; right ^= cbcright2;}}
     tempresult += String.fromCharCode ((left>>>24), ((left>>>16) & 0xff), ((left>>>8) & 0xff), (left & 0xff), (right>>>24), ((right>>>16) & 0xff), ((right>>>8) & 0xff), (right & 0xff));

     chunk += 8;
     if (chunk == 512) {result += tempresult; tempresult = ""; chunk = 0;}
   } //for every 8 characters, or 64 bits in the message

   //return the result as an array
   return result + tempresult;
} //end of des

//
// Print Hex Array
//
cryptoObject.printHex = function( s )
{
 var r = "0x";
   var hexes = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
   for (var i=0; i<s.length; i++) {r += hexes [s.charCodeAt(i) >> 4] + hexes [s.charCodeAt(i) & 0xf];}
   return r;
}

//
// Print UnHex Array
//
cryptoObject.unHex = function( s )
{
 var r = "";
   for (var i=2; i<s.length;i+=2) {
    x1 = s.charCodeAt(i);
    x1 = x1 >= 48 && x1 < 58 ? x1 - 48 : x1 - 97 + 10;
    x2 = s.charCodeAt(i+1);
    x2 = x2 >= 48 && x2 < 58 ? x2 - 48 : x2 - 97 + 10;
    r += String.fromCharCode (((x1 << 4) & 0xF0) | (x2 & 0x0F));
   }

   return r;
}

//
// Client Random Key 생성
//

cryptoObject.getRandomKey = function( digits )
{
 var rndKey, nIndex;

 rndKey = "";

 do
 {
  nIndex = Math.floor( Math.random() * cryptoObject.KeyStr.length ) + 1;
  rndKey = rndKey + cryptoObject.KeyStr.substr( nIndex, 1 );
 }
 while ( rndKey.length < digits )

 return rndKey;
}

Posted by 1010
반응형
/^[a-z0-9_]{4,20}$/;
Posted by 1010
반응형
 


네이버나 포탈사이트 등을 방문 하다보면 위와같이

앞글자 혹은 중간글자만 쳐도 나머지 글자들이 나오는 화면을 볼수있는데

이를 자동완성기능 혹은 autocomplete 라고 한다..

기본적으로 브라우저내에서 자동완성기능을 지원하긴 하지만

DB와 연동해서 뿌려주는 기능은 별도 제작을 해야한다.

캐릭터셋이 utf-8 이냐 euc kr 이냐에 따라서도 사용방법이 약간은 다르다.

아래는 간단한 예제와 샘플파일이다.


위 파일은 autocomplete 기능을 사용하게 해주는 plug in 이며

jquery.com 의 plugins 에서도 다운이 가능하다.

우선 jquery 스크립트를 넣어준 뒤 위 플러그인을 삽입해주면 된다.

<?include "data_js.php";?>

<SCRIPT type="text/javascript" src="../jquery/jquery-1.4.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="./autocomplete/jquery.autocomplete.css"/>
<script type="text/javascript" src="./autocomplete/jquery.autocomplete.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#search").autocomplete(goods,{
  matchContains: true
 });
});
</script>

<input type="text" id="search" autocomplete="off">

* 상세소스는 http://jaweb.co.kr/jstudy/18.php 접속후 소스보기하면 다 나오는데
위의 소스만으로도 구동에는 전혀 문제가 없다.


위 내용은 search 라는 id 필드는 autocomplete 기능을 사용할 것이고

데이터는 goods 데이터를 기반으로 내용중 일부라도 맞는경우 (matchContains: true)

보여지게 하겠다는 속성이다.

데이터(goods)를 가져올때는 여러가지 방법이 있는데

난 DB에서 데이터 이용방법과 js 파일 생성방식 두가지로 선택했다.


data_js.php 파일은  단순하게 파일내에 입력을 하게되면 알아서 적용된다. (내용이 간단하니 파일을 참고하면 좋다.)


data_db.php 파일은 db셋팅이 되어있는 파일내에서 어느부분인지를 선택 한 뒤 작업을 해주면 된다.

헌데 소스내용을 보면 굳이 urlencode 를 해서 array_push로 배열안에 값을 넣고

실제 뿌려줄때는 urldecode 를 해서 json 방식으로 다시 인코딩 한 뒤 값을 뿌려준다.

urlencode 의 사용목적은 바로 한글문제..

utf-8 환경에선 urlencode 없이도 무리없이 정상작동 하지만

euckr 환경에선 글씨가 깨져서 들어가거나

null값으로 출력이되어 오류가 나게 된다.


그럴때 json으로 인코딩을 하기 전 urlencode 로 한번 인코딩을 해주고

실제 뿌려줄때 decode를 안하게되면 %45%D 이런식으로 문자가 깨져서 보이기에

글씨 깨짐을 방지하기 위해서 위와같이 작업을 한것이다.


autocomplete 플러그인 내에서는 지원하는 기능이 내가 설명한 정도보다는 훨씬 많다.

줄에 맞춰서 값을 가져오거나

key값에 따라 값을 뿌려주는 기능...

이미지를 이용 출력해는 기능 등~   (참고 : http://jaweb.nayana.com/search.php   우측상단 펫 검색란에 1,2 등을 치거나 펫 이름을 치면 결과가 나오는데.. jquery 처음 배울때 작업한 것이라 소스가 상당히 조잡한 편이다.)

쓸데가 상당히 많아보이는 플러그인이니 공부할때 참고하면 좋을 것 같다.


출처 : http://jaweb.tistory.com/159

------------------------------------------------------

Ajax AutoComplete for jQuery

AutoComplete is like Magic!

Ajax Autocomplete for jQuery allows you to easily create autocomplete/autosuggest boxes for text input fields.

It is built with focus on performance. Results for every query are cached and pulled from local cache for the same repeating query. If there are no results for particular query it stops sending requests to the server for other queries with the same root.

Demo

Ajax autosuggest sample (start typing country name):


Local(no ajax) autosuggest sample (start typing month name):

Suggest:   

Note: Delimiter support has been added in v1.0.5. Try separate countries by "," or ";".

What's New in 1.1

$('#query').autocomplete(options) now returns an Autocomplete instance only for the first matched element.

Autocomplete functionality can be disabled or enabled programmatically.

var ac = $('#query').autocomplete(options);
ac.disable();
ac.enable();

Options can be changed programmatically at any time, only options that are passed get set:

ac.setOptions({ zIndex: 1001 });

If you need to pass additional parameters, you can set them via setOptions too:

ac.setOptions({ params: { first:'John', last:'Doe' } });

New parameters when initializing autocomplete. They can also be set via setOptions.

- zIndex: default value is 9999.

- fnFormatResult: function that formats values that are displayed in the autosuggest list. It takes three parameters: suggested value, data and current query value. Default function for this:

var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

function fnFormatResult(value, data, currentValue) {
  var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
  return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
}

Installation

Include jQuery in your header. After its included, add autocomplete script.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>

How to Use

Here is an Ajax Autocomplete sample for the text field with id "query"

<input type="text" name="q" id="query" />

Create an instance of the Autocomplete object. You can have multiple instances on a single page.

Important: Autocomplete must be initialized after DOM has finished loading. Otherwise you will get an error in IE.

var options, a;
jQuery(function(){
  options = { serviceUrl:'service/autocomplete.ashx' };
  a = $('#query').autocomplete(options);
});

You can add extra options:

  var a = $('#query').autocomplete({ 
    serviceUrl:'service/autocomplete.ashx',
    minChars:2, 
    delimiter: /(,|;)\s*/, // regex or character
    maxHeight:400,
    width:300,
    zIndex: 9999,
    deferRequestBy: 0, //miliseconds
    params: { country:'Yes' }, //aditional parameters
    noCache: false, //default is false, set to true to disable caching
    // callback function:
    onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
    // local autosugest options:
    lookup: ['January', 'February', 'March', 'April', 'May'] //local lookup values 
  });

Use lookup option only if you prefer to inject an array of autocompletion options, rather than sending Ajax queries.

Web page that provides data for Ajax Autocomplete, in our case autocomplete.ashx will receive GET request with querystring ?query=Li, and it must return JSON data in the following format:

{
 query:'Li',
 suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
 data:['LR','LY','LI','LT']
}

Notes:

  • query - original query value
  • suggestions - comma separated array of suggested values
  • data (optional) - data array, that contains values for callback function when data is selected.

Styling

Script generates the following HTML (sample query Li). Active element when you navigate up and down is marked with class "selected". You can style it any way you wish.

<div class="autocomplete-w1">
  <div style="width:299px;" id="Autocomplete_1240430421731" class="autocomplete">
    <div><strong>Li</strong>beria</div>
    <div><strong>Li</strong>byan Arab Jamahiriya</div>
    <div><strong>Li</strong>echtenstein</div>
    <div class="selected"><strong>Li</strong>thuania</div>
  </div>
</div>

Here is style used in the sample above:

.autocomplete-w1 { background:url(img/shadow.png) no-repeat bottom right; position:absolute; top:0px; left:0px; margin:6px 0 0 6px; /* IE6 fix: */ _background:none; _margin:1px 0 0 0; }
.autocomplete { border:1px solid #999; background:#FFF; cursor:default; text-align:left; max-height:350px; overflow:auto; margin:-6px 6px 6px -6px; /* IE6 specific: */ _height:350px;  _margin:0; _overflow-x:hidden; }
.autocomplete .selected { background:#F0F0F0; }
.autocomplete div { padding:2px 5px; white-space:nowrap; overflow:hidden; }
.autocomplete strong { font-weight:normal; color:#3399FF; }

If you will use this CSS, please make sure to correct path to the shadow.png image. Image is included in the package. It uses CSS Drop Shadow technique by Sergio Villarreal.

Download

Download Ajax AutoComplete for jQuery

Download DevBridge Ajax Autocomplete v1.1.3 for jQuery

Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.

Currently supported browsers: IE 7+, FF 2+, Safari 3+, Opera 9+


Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Posted by 1010
반응형
누가 물어봐서 찾아본 김에 그냥 정리합니다. 아시다시피 Javascript는 명시적인 타입정의가 없습니다. int나 String같이 타입을 명시해서 변수를 정의하지 않고 그냥 var타입으로 정의하면 Javascript가 알아서 적절한 타입을 지정합니다. 명시적인 타입이 없다는건 때론 타입때문에 헷갈리기도 하고 원치 않는 결과가 나타나기도 합니다.

그래서 보통은 약간 편법적인 방법으로 String을 Number로 바꾼다던지 Number를 String으로 바꾼다던지 합니다.

  1. // 숫자를 스트링로 바꾸기  
  2. var tt = 2  
  3. tt += "";  
  4. alert(typeof tt);   // Result : string  
  5.  
  6. // 스트링을 숫자로 바꾸기  
  7. tt = "2" 
  8. tt *= 1;  
  9. alert(typeof tt);    // Result : number  

위의 방법이 가장 간단하게 형변환을 하는 방법입니다. 쉽게 자바스크립트의 자동형변환을 이용한 겁니다. 숫자타입에 문자열을 더하면 결과가 문자열이 되고 문자열에 숫자를 곱하면 숫자타입이 되는 특성을 이용해서 결과는 달라지지 않게 타입만 변환되도록 한 것입니다.

해본 사람을 보면 알기는 하겠지만 잘 모르는 사람이 보면 어떤 의도로 한 소스인지 명확하지 않은 단점이 있기도 하고 좀더 명시적으로 타입변환이 필요할 때가 있습니다.

  1. // 숫자를 스트링로 바꾸기  
  2. var tt = 2  
  3. alert(typeof tt);    // Result : number  
  4. tt = String(tt);  
  5. alert(typeof tt);    // Result : string  
  6.  
  7. // 스트링을 숫자로 바꾸기  
  8. tt = "2" 
  9. alert(typeof tt);    // Result : string  
  10. tt = Number(tt);  
  11. alert(typeof tt);    // Result : number  

타입변환을 하는 함수인 Number()와 String()을 이용한 소스입니다.



또한 아래처럼 parseInt()나 parseFloat()를 이용해서도 형변환을 할 수 있습니다. 함수명에서 알 수 있듯이 parseInt()는 Integer타입으로 변환을 하고 parseFloat()는 Float타입으로 변환을 합니다.
  1. var tt = "2" 
  2. alert(typeof tt);    // Result : string  
  3. tt = parseInt(tt);  
  4. alert(typeof tt);    // Result : number  
  5.               
  6. tt = "2" 
  7. alert(typeof tt);    // Result : string  
  8. tt = parseFloat(tt);  
  9. alert(typeof tt);    // Result : number  

parseInt()나 parseFloat()는 형변환 자체가 목적은 아니기 때문에 얘기가 나온 김에 좀 더 살펴보겠습니다. parseIn()와 parseFloat()는 정수와 실수로 파싱해 주는 역할을 하고 있습니다.

parseInt(string, radix)
parseFloat(string)

API정의를 보면 위처럼 정의되어 있습니다. parseInt()에서 radix는 기수로 parse할 때 기준이 되는 진수입니다. 정수로 파싱하는 parseInt에만 정의되어 있습니다. 2~ 36진수까지를 정의할 수 있고 optional값으로 없을 경우 10진수로 parse합니다.

  1. parseInt("123.456");        // 123  
  2. parseInt("100mile");        // 100  
  3. parseInt("w25");               // NaN  
  4. parseInt("05");                  // 5  
  5. parseInt("09");                  // 0  
  6. parseInt("0x35");              // 53  
  7. parseInt("1101", 2);         // 13  
  8. parseInt("09", 10);            // 9  
  9. parseInt("10", 8);              // 8  
  10.  
  11. parseFloat("123.456");       // 123.456  
  12. parseFloat("100.5mile");    // 100.5  
  13. parseFloat("w25");               // NaN  
  14. parseFloat("05");                  // 5  
  15. parseFloat("09");                  // 9  
  16. parseFloat("0x35");              // 0  

Javascript에서 "0"으로 시작하는 숫자는 8진수 "0x"로 시작하는 숫자는 16진수로 정의되고 있기 때문에 5번라인에서 9가 8진수에서 사용할 수 없기 때문에 의도하지 않은 0이 나왔습니다.


출처 : http://blog.outsider.ne.kr/361
Posted by 1010
반응형
  1. XHTML1.1 에서 사용하면 안되는 것들
    1. 일반적으로 범하기 쉬운 오류
      1. 닫히지 않은 빈요소 - Not closing empty elements (elements without closing tags)
      2. 닫히지 않은 꽉 찬 요소 - Not closing non-empty elements
      3. 부적합한 함유 요소 - Improperly nesting elements (elements must be closed in reverse order)
      4. 대체 텍스트가 기술되지 않음 - Not specifying alternate text for images (using the alt attribute, which helps make pages accessible for devices that don't load images or screen-readers for the blind)
      5. 본문에 직접 텍스트를 삽입 - Putting text directly in the body of the document
      6. 인라인 요소에 블록-레벨 요소를 포함 - Nesting block-level elements within inline elements
      7. 속성 값을 인용부호로 감싸지 않음 - Not putting quotation marks around attribute values
      8. '&' 문자를 직접 사용 ('&amp;'로 대체) - Using the ampersand outside of entities (use &amp; to display the ampersand character)
      9. 태그 이름이나 태그 속성에 대문자를 사용 - Using uppercase tag names and/or tag attributes
      10. 간소화된 속성 사용 - Attribute minimization
    2. 그 외의 오류들
      1. <form 에 name속성 사용하지 못함 - 2009/02/21 07:28:08
      2. <style> 사용 불가능
      3. URL 주소에서도 '&' 문자를 직접 사용하면 안됨.
      4. <form 에서 method="POST/post"
      5. width= 엘리먼트 허용하지 않음

 

XHTML1.1 에서 사용하면 안되는 것들#

 XHTML에서 사용하면 안되는 것들이 있다. 여기에 나열해 보자.

 

일반적으로 범하기 쉬운 오류#

 아래는 일반적으로 범하기 쉬운 오류로 위키백과에 소개된 내용이다. - http://ko.wikipedia.org/wiki/XHTML

 

닫히지 않은 빈요소 - Not closing empty elements (elements without closing tags)#
  • 틀림: <br>
  • 옳음: <br />

 

닫히지 않은 꽉 찬 요소 - Not closing non-empty elements#
  • 틀림: <p>This is a paragraph.<p>This is another paragraph.
  • 옳음: <p>This is a paragraph.</p><p>This is another paragraph.</p>

 

부적합한 함유 요소 - Improperly nesting elements (elements must be closed in reverse order)#
  • 틀림: <em><strong>This is some text.</em></strong>
  • 옳음: <em><strong>This is some text.</strong></em>

 

대체 텍스트가 기술되지 않음 - Not specifying alternate text for images (using the alt attribute, which helps make pages accessible for devices that don't load images or screen-readers for the blind)#
  • 틀림: <img src="/skins/common/images/poweredby_mediawiki_88x31.png" />
  • 옳음: <img src="/skins/common/images/poweredby_mediawiki_88x31.png" alt="MediaWiki" />

 

본문에 직접 텍스트를 삽입 - Putting text directly in the body of the document#
  • 틀림: <body>Welcome to my page.</body>
  • 옳음: <body><p>Welcome to my page.</p></body>

 

인라인 요소에 블록-레벨 요소를 포함 - Nesting block-level elements within inline elements#
  • 틀림: <em><h2>Introduction</h2></em>
  • 옳음: <h2><em>Introduction</em></h2>

 

속성 값을 인용부호로 감싸지 않음 - Not putting quotation marks around attribute values#
  • 틀림: <td rowspan=3>
  • 옳음: <td rowspan="3">

 

'&' 문자를 직접 사용 ('&amp;'로 대체) - Using the ampersand outside of entities (use &amp; to display the ampersand character)#
  • 틀림: <title>Cars & Trucks</title>
  • 옳음: <title>Cars &amp; Trucks</title>

 

태그 이름이나 태그 속성에 대문자를 사용 - Using uppercase tag names and/or tag attributes#
  • 틀림: <BODY><P>The Best Page Ever</P></BODY>
  • 옳음: <body><p>The Best Page Ever</p></body>

 

간소화된 속성 사용 - Attribute minimization#
  • 틀림: <textarea readonly>READ-ONLY</textarea>
  • 옳음: <textarea readonly="readonly">READ-ONLY</textarea>

 

 

그 외의 오류들#

 그 외에 직접 작정하면서 오류가 났던 부분을 정리한다.

 

<form 에 name속성 사용하지 못함 - 2009/02/21 07:28:08#
  • 흔히 <form name="fname" ... 이런식으로 정의해서 사용하지만 form에 name속성은 원래 허용하지 않는 속성인가보다. id속성은 무관하니 id로 해결해야 겠다.

 

<style> 사용 불가능#
  • css파일 이외의 style은 사용불가능 하다. 대신 inline style은 허용하니 inline 아니면 css파일로 스타일을 정의해야 한다.

 

URL 주소에서도 '&' 문자를 직접 사용하면 안됨.#
  • URL 링크를 생성하는데에도.. &문자를 바로 사용불가능함.
  • & => &amp; 바꾸어야함.

 

<form 에서 method="POST/post"#
  • form 태그에서 method정의시 대문자를 입력하면 안된 post/get과 같이 소문자로만 입력해야 함

 

td width= 어트리뷰트 허용하지 않음#
  • 보통 <td width 이런식으로 너비를 정하지만 이렇게 정의하지 못하게 되어 있음
  • <td>태그에서는 width 어트리뷰트를 허용하지 않음
  • Attribute "width" exists, but can not be used for this element. 에러를 낸다.



출처 : http://bequietzero.springnote.com/pages/2758810

 

Posted by 1010
반응형
<input type="text" autocomplete="off"/> <- 직접 기술한 건 잘못된 예


<input type="text" onfocus="this.setAttribute('autocomplete', 'off');"   /> <- 올바른 방법

Posted by 1010
반응형

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
 function test(obj){
  var tc = document.getElementsByName(obj.name);
  for(var i=0; tc.length; i++){
   if(tc[i] == obj){
    var j = i;
    break;
   }
  }
  alert(j);

 }
//-->
</SCRIPT>
 <BODY>
  <INPUT TYPE="text" NAME="aaa" ONCLICK="test(this);"><INPUT TYPE="button" name="btn" VALUE="" ONCLICK="test(this);">
   <INPUT TYPE="text" NAME="aaa" ONCLICK="test(this);"><INPUT TYPE="button"  name="btn" VALUE="" ONCLICK="test(this);">
 </BODY>
</HTML>

Posted by 1010
반응형
디비에 넣을때 변환

String contents = comment.getContent().replace( "\r\n", "<BR/>" );
comment.setContent(contents);


화면상에 뿌려줄때 변환 (수정모드시)
String contents = qnaComment.getContent().replace( "<BR/>", "\r\n" );
qnaComment.setContent(contents);

일반화면
<%=contents>
Posted by 1010
반응형
<html>
  <head>
    <!--
      CryptoMX Tools
      Copyright (C) 2004 - 3005 Derek Buitenhuis

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation; either version 2
      of the License, or (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -->
    <title>DES Crypt</title>
    <!-- des.js -->
   
    <script language="Javascript">
function dP(){
  salt=document.CRYPT.Salt.value;
  pw_salt=this.crypt(salt,document.CRYPT.PW.value);

  document.CRYPT.ENC_PW.value=pw_salt[0];
  document.CRYPT.Salt.value=pw_salt[1];
  return false;
}

function bTU(b){
      value=Math.floor(b);
      return (value>=0?value:value+256);
}
function fBTI(b,offset){
      value=this.byteToUnsigned(b[offset++]);
      value|=(this.byteToUnsigned(b[offset++])<<8);
      value|=(this.byteToUnsigned(b[offset++])<<16);
      value|=(this.byteToUnsigned(b[offset++])<<24);
      return value;
}
function iTFB(iValue,b,offset){
      b[offset++]=((iValue)&0xff);
      b[offset++]=((iValue>>>8)&0xff);
      b[offset++]=((iValue>>>16)&0xff);
      b[offset++]=((iValue>>>24)&0xff);
}
function P_P(a,b,n,m,results){
      t=((a>>>n)^b)&m;
      a^=t<<n;
      b^=t;
      results[0]=a;
      results[1]=b;
}
function H_P(a,n,m){
      t=((a<<(16-n))^a)&m;
      a=a^t^(t>>>(16-n));
      return a;
}
function d_s_k(key){
      schedule=new Array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
      c=this.fourBytesToInt(key,0);
      d=this.fourBytesToInt(key,4);
      results=new Array(0,0);
      this.PERM_OP(d,c,4,0x0f0f0f0f,results);
      d=results[0];c=results[1];
      c=this.HPERM_OP(c,-2,0xcccc0000);
      d=this.HPERM_OP(d,-2,0xcccc0000);
      this.PERM_OP(d,c,1,0x55555555,results);
      d=results[0];c=results[1];
      this.PERM_OP(c,d,8,0x00ff00ff,results);
      c=results[0];d=results[1];
      this.PERM_OP(d,c,1,0x55555555,results);
      d=results[0];c=results[1];
      d=(((d&0x000000ff)<<16)|(d&0x0000ff00)|((d&0x00ff0000)>>>16)|((c&0xf0000000)>>>4));
      c&=0x0fffffff;
      s=0;t=0;
      j=0;
      for(i=0;i<this.ITERATIONS;i++){
         if(this.shifts2[i]){
            c=(c>>>2)|(c<<26);
            d=(d>>>2)|(d<<26);
         }else{
            c=(c>>>1)|(c<<27);
            d=(d>>>1)|(d<<27);
         }
         c&=0x0fffffff;
         d&=0x0fffffff;
         s=this.skb[0][c&0x3f]|this.skb[1][((c>>>6)&0x03)|((c>>>7)&0x3c)]|this.skb[2][((c>>>13)&0x0f)|((c>>>14)&0x30)]|this.skb[3][((c>>>20)&0x01)|((c>>>21)&0x06)|((c>>>22)&0x38)];
         t=this.skb[4][d&0x3f]|this.skb[5][((d>>>7)&0x03)|((d>>>8)&0x3c)]|this.skb[6][(d>>>15)&0x3f]|this.skb[7][((d>>>21)&0x0f)|((d>>>22)&0x30)];
         schedule[j++]=((t<< 16)|(s&0x0000ffff))&0xffffffff;
         s=((s>>>16)|(t&0xffff0000));
         s=(s<<4)|(s>>>28);
         schedule[j++]=s&0xffffffff;
      }
      return schedule;
}
function D_E(L,R,S,E0,E1,s){
      v=R^(R>>>16);
      u=v&E0;
      v=v&E1;
      u=(u^(u<<16))^R^s[S];
      t=(v^(v<<16))^R^s[S+1];
      t=(t>>>4)|(t<<28);
      L^=this.SPtrans[1][t&0x3f]|this.SPtrans[3][(t>>>8)&0x3f]|this.SPtrans[5][(t>>>16)&0x3f]|this.SPtrans[7][(t>>>24)&0x3f]|this.SPtrans[0][u&0x3f]|this.SPtrans[2][(u>>>8)&0x3f]|this.SPtrans[4][(u>>>16)&0x3f]|this.SPtrans[6][(u>>>24)&0x3f];
      return L;
}
function bdy(schedule,Eswap0,Eswap1) {
  left=0;
  right=0;
  t=0;
      for(j=0;j<25;j++){
         for(i=0;i<this.ITERATIONS*2;i+=4){
            left=this.D_ENCRYPT(left, right,i,Eswap0,Eswap1,schedule);
            right=this.D_ENCRYPT(right,left,i+2,Eswap0,Eswap1,schedule);
         }
         t=left;
         left=right;
         right=t;
      }
      t=right;
      right=(left>>>1)|(left<<31);
      left=(t>>>1)|(t<<31);
      left&=0xffffffff;
      right&=0xffffffff;
      results=new Array(0,0);
      this.PERM_OP(right,left,1,0x55555555,results);
      right=results[0];left=results[1];
      this.PERM_OP(left,right,8,0x00ff00ff,results);
      left=results[0];right=results[1];
      this.PERM_OP(right,left,2,0x33333333,results);
      right=results[0];left=results[1];
      this.PERM_OP(left,right,16,0x0000ffff,results);
      left=results[0];right=results[1];
      this.PERM_OP(right,left,4,0x0f0f0f0f,results);
      right=results[0];left=results[1];
      out=new Array(0,0);
      out[0]=left;out[1]=right;
      return out;
}
function rC(){ return this.GOODCHARS[Math.floor(64*Math.random())]; }
function cript(salt,original){
  if(salt.length>=2) salt=salt.substring(0,2);
  while(salt.length<2) salt+=this.randChar();
  re=new RegExp("[^./a-zA-Z0-9]","g");
  if(re.test(salt)) salt=this.randChar()+this.randChar();
  charZero=salt.charAt(0)+'';
      charOne=salt.charAt(1)+'';
  ccZ=charZero.charCodeAt(0);
  ccO=charOne.charCodeAt(0);
  buffer=charZero+charOne+"           ";
      Eswap0=this.con_salt[ccZ];
      Eswap1=this.con_salt[ccO]<<4;
      key=new Array(0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0);
      for(i=0;i<key.length&&i<original.length;i++){
         iChar=original.charCodeAt(i);
         key[i]=iChar<<1;
      }
      schedule=this.des_set_key(key);
      out=this.body(schedule,Eswap0,Eswap1);
      b=new Array(0,0,0,0,0,0,0,0,0);
      this.intToFourBytes(out[0],b,0);
      this.intToFourBytes(out[1],b,4);
      b[8]=0;
      for(i=2,y=0,u=0x80;i<13;i++){
         for(j=0,c=0;j<6;j++){
            c<<=1;
            if((b[y]&u)!=0) c|=1;
            u>>>=1;
            if(u==0){
               y++;
               u=0x80;
            }
            buffer=buffer.substring(0,i)+String.fromCharCode(this.cov_2char[c])+buffer.substring(i+1,buffer.length);
         }
      }
  ret=new Array(buffer,salt);
      return ret;
}

function Crypt() {
this.ITERATIONS=16;
this.GOODCHARS=new Array(
  ".","/","0","1","2","3","4","5","6","7",
  "8","9","A","B","C","D","E","F","G","H",
  "I","J","K","L","M","N","O","P","Q","R",
  "S","T","U","V","W","X","Y","Z","a","b",
  "c","d","e","f","g","h","i","j","k","l",
  "m","n","o","p","q","r","s","t","u","v",
  "w","x","y","z");
this.con_salt=new Array(
  0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
      0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
      0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
      0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
      0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
      0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,
      0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
      0x0A,0x0B,0x05,0x06,0x07,0x08,0x09,0x0A,
      0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,
      0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,
      0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,
      0x23,0x24,0x25,0x20,0x21,0x22,0x23,0x24,
      0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,
      0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,
      0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,
      0x3D,0x3E,0x3F,0x00,0x00,0x00,0x00,0x00 );
this.shifts2=new Array(
  false,false,true,true,true,true,true,true,
  false,true, true,true,true,true,true,false );
this.skb=new Array(0,0,0,0,0,0,0,0);
  this.skb[0]=new Array(
         0x00000000,0x00000010,0x20000000,0x20000010,
         0x00010000,0x00010010,0x20010000,0x20010010,
         0x00000800,0x00000810,0x20000800,0x20000810,
         0x00010800,0x00010810,0x20010800,0x20010810,
         0x00000020,0x00000030,0x20000020,0x20000030,
         0x00010020,0x00010030,0x20010020,0x20010030,
         0x00000820,0x00000830,0x20000820,0x20000830,
         0x00010820,0x00010830,0x20010820,0x20010830,
         0x00080000,0x00080010,0x20080000,0x20080010,
         0x00090000,0x00090010,0x20090000,0x20090010,
         0x00080800,0x00080810,0x20080800,0x20080810,
         0x00090800,0x00090810,0x20090800,0x20090810,
         0x00080020,0x00080030,0x20080020,0x20080030,
         0x00090020,0x00090030,0x20090020,0x20090030,
         0x00080820,0x00080830,0x20080820,0x20080830,
         0x00090820,0x00090830,0x20090820,0x20090830 );
  this.skb[1]=new Array(
         0x00000000,0x02000000,0x00002000,0x02002000,
         0x00200000,0x02200000,0x00202000,0x02202000,
         0x00000004,0x02000004,0x00002004,0x02002004,
         0x00200004,0x02200004,0x00202004,0x02202004,
         0x00000400,0x02000400,0x00002400,0x02002400,
         0x00200400,0x02200400,0x00202400,0x02202400,
         0x00000404,0x02000404,0x00002404,0x02002404,
         0x00200404,0x02200404,0x00202404,0x02202404,
         0x10000000,0x12000000,0x10002000,0x12002000,
         0x10200000,0x12200000,0x10202000,0x12202000,
         0x10000004,0x12000004,0x10002004,0x12002004,
         0x10200004,0x12200004,0x10202004,0x12202004,
         0x10000400,0x12000400,0x10002400,0x12002400,
         0x10200400,0x12200400,0x10202400,0x12202400,
         0x10000404,0x12000404,0x10002404,0x12002404,
         0x10200404,0x12200404,0x10202404,0x12202404 );
  this.skb[2]=new Array(
         0x00000000,0x00000001,0x00040000,0x00040001,
         0x01000000,0x01000001,0x01040000,0x01040001,
         0x00000002,0x00000003,0x00040002,0x00040003,
         0x01000002,0x01000003,0x01040002,0x01040003,
         0x00000200,0x00000201,0x00040200,0x00040201,
         0x01000200,0x01000201,0x01040200,0x01040201,
         0x00000202,0x00000203,0x00040202,0x00040203,
         0x01000202,0x01000203,0x01040202,0x01040203,
         0x08000000,0x08000001,0x08040000,0x08040001,
         0x09000000,0x09000001,0x09040000,0x09040001,
         0x08000002,0x08000003,0x08040002,0x08040003,
         0x09000002,0x09000003,0x09040002,0x09040003,
         0x08000200,0x08000201,0x08040200,0x08040201,
         0x09000200,0x09000201,0x09040200,0x09040201,
         0x08000202,0x08000203,0x08040202,0x08040203,
         0x09000202,0x09000203,0x09040202,0x09040203 );
  this.skb[3]=new Array(
         0x00000000,0x00100000,0x00000100,0x00100100,
         0x00000008,0x00100008,0x00000108,0x00100108,
         0x00001000,0x00101000,0x00001100,0x00101100,
         0x00001008,0x00101008,0x00001108,0x00101108,
         0x04000000,0x04100000,0x04000100,0x04100100,
         0x04000008,0x04100008,0x04000108,0x04100108,
         0x04001000,0x04101000,0x04001100,0x04101100,
         0x04001008,0x04101008,0x04001108,0x04101108,
         0x00020000,0x00120000,0x00020100,0x00120100,
         0x00020008,0x00120008,0x00020108,0x00120108,
         0x00021000,0x00121000,0x00021100,0x00121100,
         0x00021008,0x00121008,0x00021108,0x00121108,
         0x04020000,0x04120000,0x04020100,0x04120100,
         0x04020008,0x04120008,0x04020108,0x04120108,
         0x04021000,0x04121000,0x04021100,0x04121100,
         0x04021008,0x04121008,0x04021108,0x04121108 );
  this.skb[4]=new Array(
         0x00000000,0x10000000,0x00010000,0x10010000,
         0x00000004,0x10000004,0x00010004,0x10010004,
         0x20000000,0x30000000,0x20010000,0x30010000,
         0x20000004,0x30000004,0x20010004,0x30010004,
         0x00100000,0x10100000,0x00110000,0x10110000,
         0x00100004,0x10100004,0x00110004,0x10110004,
         0x20100000,0x30100000,0x20110000,0x30110000,
         0x20100004,0x30100004,0x20110004,0x30110004,
         0x00001000,0x10001000,0x00011000,0x10011000,
         0x00001004,0x10001004,0x00011004,0x10011004,
         0x20001000,0x30001000,0x20011000,0x30011000,
         0x20001004,0x30001004,0x20011004,0x30011004,
         0x00101000,0x10101000,0x00111000,0x10111000,
         0x00101004,0x10101004,0x00111004,0x10111004,
         0x20101000,0x30101000,0x20111000,0x30111000,
         0x20101004,0x30101004,0x20111004,0x30111004 );
  this.skb[5]=new Array(
         0x00000000,0x08000000,0x00000008,0x08000008,
         0x00000400,0x08000400,0x00000408,0x08000408,
         0x00020000,0x08020000,0x00020008,0x08020008,
         0x00020400,0x08020400,0x00020408,0x08020408,
         0x00000001,0x08000001,0x00000009,0x08000009,
         0x00000401,0x08000401,0x00000409,0x08000409,
         0x00020001,0x08020001,0x00020009,0x08020009,
         0x00020401,0x08020401,0x00020409,0x08020409,
         0x02000000,0x0A000000,0x02000008,0x0A000008,
         0x02000400,0x0A000400,0x02000408,0x0A000408,
         0x02020000,0x0A020000,0x02020008,0x0A020008,
         0x02020400,0x0A020400,0x02020408,0x0A020408,
         0x02000001,0x0A000001,0x02000009,0x0A000009,
         0x02000401,0x0A000401,0x02000409,0x0A000409,
         0x02020001,0x0A020001,0x02020009,0x0A020009,
         0x02020401,0x0A020401,0x02020409,0x0A020409 );
  this.skb[6]=new Array(
         0x00000000,0x00000100,0x00080000,0x00080100,
         0x01000000,0x01000100,0x01080000,0x01080100,
         0x00000010,0x00000110,0x00080010,0x00080110,
         0x01000010,0x01000110,0x01080010,0x01080110,
         0x00200000,0x00200100,0x00280000,0x00280100,
         0x01200000,0x01200100,0x01280000,0x01280100,
         0x00200010,0x00200110,0x00280010,0x00280110,
         0x01200010,0x01200110,0x01280010,0x01280110,
         0x00000200,0x00000300,0x00080200,0x00080300,
         0x01000200,0x01000300,0x01080200,0x01080300,
         0x00000210,0x00000310,0x00080210,0x00080310,
         0x01000210,0x01000310,0x01080210,0x01080310,
         0x00200200,0x00200300,0x00280200,0x00280300,
         0x01200200,0x01200300,0x01280200,0x01280300,
         0x00200210,0x00200310,0x00280210,0x00280310,
         0x01200210,0x01200310,0x01280210,0x01280310 );
  this.skb[7]=new Array(
         0x00000000,0x04000000,0x00040000,0x04040000,
         0x00000002,0x04000002,0x00040002,0x04040002,
         0x00002000,0x04002000,0x00042000,0x04042000,
         0x00002002,0x04002002,0x00042002,0x04042002,
         0x00000020,0x04000020,0x00040020,0x04040020,
         0x00000022,0x04000022,0x00040022,0x04040022,
         0x00002020,0x04002020,0x00042020,0x04042020,
         0x00002022,0x04002022,0x00042022,0x04042022,
         0x00000800,0x04000800,0x00040800,0x04040800,
         0x00000802,0x04000802,0x00040802,0x04040802,
         0x00002800,0x04002800,0x00042800,0x04042800,
         0x00002802,0x04002802,0x00042802,0x04042802,
         0x00000820,0x04000820,0x00040820,0x04040820,
         0x00000822,0x04000822,0x00040822,0x04040822,
         0x00002820,0x04002820,0x00042820,0x04042820,
         0x00002822,0x04002822,0x00042822,0x04042822 );
this.SPtrans=new Array(0,0,0,0,0,0,0,0);
  this.SPtrans[0]=new Array(
         0x00820200,0x00020000,0x80800000,0x80820200,
         0x00800000,0x80020200,0x80020000,0x80800000,
         0x80020200,0x00820200,0x00820000,0x80000200,
         0x80800200,0x00800000,0x00000000,0x80020000,
         0x00020000,0x80000000,0x00800200,0x00020200,
         0x80820200,0x00820000,0x80000200,0x00800200,
         0x80000000,0x00000200,0x00020200,0x80820000,
         0x00000200,0x80800200,0x80820000,0x00000000,
         0x00000000,0x80820200,0x00800200,0x80020000,
         0x00820200,0x00020000,0x80000200,0x00800200,
         0x80820000,0x00000200,0x00020200,0x80800000,
         0x80020200,0x80000000,0x80800000,0x00820000,
         0x80820200,0x00020200,0x00820000,0x80800200,
         0x00800000,0x80000200,0x80020000,0x00000000,
         0x00020000,0x00800000,0x80800200,0x00820200,
         0x80000000,0x80820000,0x00000200,0x80020200 );
  this.SPtrans[1]=new Array(
         0x10042004,0x00000000,0x00042000,0x10040000,
         0x10000004,0x00002004,0x10002000,0x00042000,
         0x00002000,0x10040004,0x00000004,0x10002000,
         0x00040004,0x10042000,0x10040000,0x00000004,
         0x00040000,0x10002004,0x10040004,0x00002000,
         0x00042004,0x10000000,0x00000000,0x00040004,
         0x10002004,0x00042004,0x10042000,0x10000004,
         0x10000000,0x00040000,0x00002004,0x10042004,
         0x00040004,0x10042000,0x10002000,0x00042004,
         0x10042004,0x00040004,0x10000004,0x00000000,
         0x10000000,0x00002004,0x00040000,0x10040004,
         0x00002000,0x10000000,0x00042004,0x10002004,
         0x10042000,0x00002000,0x00000000,0x10000004,
         0x00000004,0x10042004,0x00042000,0x10040000,
         0x10040004,0x00040000,0x00002004,0x10002000,
         0x10002004,0x00000004,0x10040000,0x00042000 );
  this.SPtrans[2]=new Array(
         0x41000000,0x01010040,0x00000040,0x41000040,
         0x40010000,0x01000000,0x41000040,0x00010040,
         0x01000040,0x00010000,0x01010000,0x40000000,
         0x41010040,0x40000040,0x40000000,0x41010000,
         0x00000000,0x40010000,0x01010040,0x00000040,
         0x40000040,0x41010040,0x00010000,0x41000000,
         0x41010000,0x01000040,0x40010040,0x01010000,
         0x00010040,0x00000000,0x01000000,0x40010040,
         0x01010040,0x00000040,0x40000000,0x00010000,
         0x40000040,0x40010000,0x01010000,0x41000040,
         0x00000000,0x01010040,0x00010040,0x41010000,
         0x40010000,0x01000000,0x41010040,0x40000000,
         0x40010040,0x41000000,0x01000000,0x41010040,
         0x00010000,0x01000040,0x41000040,0x00010040,
         0x01000040,0x00000000,0x41010000,0x40000040,
         0x41000000,0x40010040,0x00000040,0x01010000 );
  this.SPtrans[3]=new Array(
         0x00100402,0x04000400,0x00000002,0x04100402,
         0x00000000,0x04100000,0x04000402,0x00100002,
         0x04100400,0x04000002,0x04000000,0x00000402,
         0x04000002,0x00100402,0x00100000,0x04000000,
         0x04100002,0x00100400,0x00000400,0x00000002,
         0x00100400,0x04000402,0x04100000,0x00000400,
         0x00000402,0x00000000,0x00100002,0x04100400,
         0x04000400,0x04100002,0x04100402,0x00100000,
         0x04100002,0x00000402,0x00100000,0x04000002,
         0x00100400,0x04000400,0x00000002,0x04100000,
         0x04000402,0x00000000,0x00000400,0x00100002,
         0x00000000,0x04100002,0x04100400,0x00000400,
         0x04000000,0x04100402,0x00100402,0x00100000,
         0x04100402,0x00000002,0x04000400,0x00100402,
         0x00100002,0x00100400,0x04100000,0x04000402,
         0x00000402,0x04000000,0x04000002,0x04100400 );
  this.SPtrans[4]=new Array(
         0x02000000,0x00004000,0x00000100,0x02004108,
         0x02004008,0x02000100,0x00004108,0x02004000,
         0x00004000,0x00000008,0x02000008,0x00004100,
         0x02000108,0x02004008,0x02004100,0x00000000,
         0x00004100,0x02000000,0x00004008,0x00000108,
         0x02000100,0x00004108,0x00000000,0x02000008,
         0x00000008,0x02000108,0x02004108,0x00004008,
         0x02004000,0x00000100,0x00000108,0x02004100,
         0x02004100,0x02000108,0x00004008,0x02004000,
         0x00004000,0x00000008,0x02000008,0x02000100,
         0x02000000,0x00004100,0x02004108,0x00000000,
         0x00004108,0x02000000,0x00000100,0x00004008,
         0x02000108,0x00000100,0x00000000,0x02004108,
         0x02004008,0x02004100,0x00000108,0x00004000,
         0x00004100,0x02004008,0x02000100,0x00000108,
         0x00000008,0x00004108,0x02004000,0x02000008 );

  this.SPtrans[5]=new Array(
         0x20000010,0x00080010,0x00000000,0x20080800,
         0x00080010,0x00000800,0x20000810,0x00080000,
         0x00000810,0x20080810,0x00080800,0x20000000,
         0x20000800,0x20000010,0x20080000,0x00080810,
         0x00080000,0x20000810,0x20080010,0x00000000,
         0x00000800,0x00000010,0x20080800,0x20080010,
         0x20080810,0x20080000,0x20000000,0x00000810,
         0x00000010,0x00080800,0x00080810,0x20000800,
         0x00000810,0x20000000,0x20000800,0x00080810,
         0x20080800,0x00080010,0x00000000,0x20000800,
         0x20000000,0x00000800,0x20080010,0x00080000,
         0x00080010,0x20080810,0x00080800,0x00000010,
         0x20080810,0x00080800,0x00080000,0x20000810,
         0x20000010,0x20080000,0x00080810,0x00000000,
         0x00000800,0x20000010,0x20000810,0x20080800,
         0x20080000,0x00000810,0x00000010,0x20080010 );
  this.SPtrans[6]=new Array(
         0x00001000,0x00000080,0x00400080,0x00400001,
         0x00401081,0x00001001,0x00001080,0x00000000,
         0x00400000,0x00400081,0x00000081,0x00401000,
         0x00000001,0x00401080,0x00401000,0x00000081,
         0x00400081,0x00001000,0x00001001,0x00401081,
         0x00000000,0x00400080,0x00400001,0x00001080,
         0x00401001,0x00001081,0x00401080,0x00000001,
         0x00001081,0x00401001,0x00000080,0x00400000,
         0x00001081,0x00401000,0x00401001,0x00000081,
         0x00001000,0x00000080,0x00400000,0x00401001,
         0x00400081,0x00001081,0x00001080,0x00000000,
         0x00000080,0x00400001,0x00000001,0x00400080,
         0x00000000,0x00400081,0x00400080,0x00001080,
         0x00000081,0x00001000,0x00401081,0x00400000,
         0x00401080,0x00000001,0x00001001,0x00401081,
         0x00400001,0x00401080,0x00401000,0x00001001 );
  this.SPtrans[7]=new Array(
         0x08200020,0x08208000,0x00008020,0x00000000,
         0x08008000,0x00200020,0x08200000,0x08208020,
         0x00000020,0x08000000,0x00208000,0x00008020,
         0x00208020,0x08008020,0x08000020,0x08200000,
         0x00008000,0x00208020,0x00200020,0x08008000,
         0x08208020,0x08000020,0x00000000,0x00208000,
         0x08000000,0x00200000,0x08008020,0x08200020,
         0x00200000,0x00008000,0x08208000,0x00000020,
         0x00200000,0x00008000,0x08000020,0x08208020,
         0x00008020,0x08000000,0x00000000,0x00208000,
         0x08200020,0x08008020,0x08008000,0x00200020,
         0x08208000,0x00000020,0x00200020,0x08008000,
         0x08208020,0x00200000,0x08200000,0x08000020,
         0x00208000,0x00008020,0x08008020,0x08200000,
         0x00000020,0x08208000,0x00208020,0x00000000,
         0x08000000,0x08200020,0x00008000,0x00208020 );
this.cov_2char=new Array(
      0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,
      0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,
      0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,
      0x4D,0x4E,0x4F,0x50,0x51,0x52,0x53,0x54,
      0x55,0x56,0x57,0x58,0x59,0x5A,0x61,0x62,
      0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,
      0x6B,0x6C,0x6D,0x6E,0x6F,0x70,0x71,0x72,
      0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A );
this.byteToUnsigned=bTU;
this.fourBytesToInt=fBTI;
this.intToFourBytes=iTFB;
this.PERM_OP=P_P;
this.HPERM_OP=H_P;
this.des_set_key=d_s_k;
this.D_ENCRYPT=D_E;
this.body=bdy;
this.randChar=rC;
this.crypt=cript;
this.displayPassword=dP;
}
Javacrypt=new Crypt();

    </script>
  </head>
  <body>
    <form name="CRYPT">
      <strong>Text: </strong><input type="text" name="PW">
      <input type="button" value="Encrypt" onClick="Javacrypt.displayPassword()"><br>
      <strong>Encrypted: </strong><input type="text" name="ENC_PW"><br>
      <strong>Salt: </strong><input type="text" name="Salt">
    </form>
    <br>
    <b>NOTE</b>: If you do not enter a salt, one will be randomly generated.
  </body>
</html>
Posted by 1010
반응형
<html>
  <head>
    <!--
      CryptoMX Tools
      Copyright (C) 2004 - 2006 Derek Buitenhuis

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation; either version 2
      of the License, or (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -->
    <title>SHA-1 Crypt</title>
  </head>
  <body>
      <!-- sha1.js -->
    <script language="JavaScript">
/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1 Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

var hexcase = 0;
var b64pad  = "";
var chrsz   = 8;

function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

function sha1_vm_test()
{
  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

function core_sha1(x, len)
{
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);
 
}

function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}  

function core_hmac_sha1(key, data)
{
  var bkey = str2binb(key);
  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
  return core_sha1(opad.concat(hash), 512 + 160);
}

function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
  return bin;
}

function binb2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask);
  return str;
}

function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}

function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

    </script>
    <form>
      <font color=#000000 size=3>Input</font>
      <input type=text name=input size=40><br>
      <font color=#000000 size=3>Result</font>
      <input type=text name=hash size=50><br>
      <input type=button value="SHA-1 It!" onclick="hash.value = hex_sha1(input.value)">
    </form>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <!--
      CryptoMX Tools
      Copyright (C) 2004 - 2006 Derek Buitenhuis

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation; either version 2
      of the License, or (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -->
    <title>MD5 Hashing</title>
  </head>
  <body>
      <!-- md5.js -->
    <script language="JavaScript">
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

var hexcase = 0;
var b64pad  = "";
var chrsz   = 8;

function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

function core_md5(x, len)
{
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

    </script>
    <form>
      <font color=#000000 size=3>Input</font>  </td><td > <input type=text name=input size=40><br>
      <font color=#000000 size=3>Result</font> </td><td > <input type=text name=hash size=40><br>
      <input type=button value="MD5 It!" onclick="hash.value = hex_md5(input.value)">
    </form>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <!--
      CryptoMX Tools
      Copyright (C) 2004 - 2006 Derek Buitenhuis

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation; either version 2
      of the License, or (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -->
    <title>MD4 Hashing</title>
  </head>
  <body>
      <!-- md4.js -->
    <script language="JavaScript">
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD4 Message
 * Digest Algorithm, as defined in RFC 1320.
 * Version 2.1 Copyright (C) Jerrad Pierce, Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

var hexcase = 0;
var b64pad  = "";
var chrsz   = 8;

function hex_md4(s){ return binl2hex(core_md4(str2binl(s), s.length * chrsz));}
function b64_md4(s){ return binl2b64(core_md4(str2binl(s), s.length * chrsz));}
function str_md4(s){ return binl2str(core_md4(str2binl(s), s.length * chrsz));}
function hex_hmac_md4(key, data) { return binl2hex(core_hmac_md4(key, data)); }
function b64_hmac_md4(key, data) { return binl2b64(core_hmac_md4(key, data)); }
function str_hmac_md4(key, data) { return binl2str(core_hmac_md4(key, data)); }

function md4_vm_test()
{
  return hex_md4("abc") == "a448017aaf21d8525fc10ae87aa6729d";
}

function core_md4(x, len)
{
  x[len >> 5] |= 0x80 << (len % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;
 
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md4_ff(a, b, c, d, x[i+ 0], 3 );
    d = md4_ff(d, a, b, c, x[i+ 1], 7 );
    c = md4_ff(c, d, a, b, x[i+ 2], 11);
    b = md4_ff(b, c, d, a, x[i+ 3], 19);
    a = md4_ff(a, b, c, d, x[i+ 4], 3 );
    d = md4_ff(d, a, b, c, x[i+ 5], 7 );
    c = md4_ff(c, d, a, b, x[i+ 6], 11);
    b = md4_ff(b, c, d, a, x[i+ 7], 19);
    a = md4_ff(a, b, c, d, x[i+ 8], 3 );
    d = md4_ff(d, a, b, c, x[i+ 9], 7 );
    c = md4_ff(c, d, a, b, x[i+10], 11);
    b = md4_ff(b, c, d, a, x[i+11], 19);
    a = md4_ff(a, b, c, d, x[i+12], 3 );
    d = md4_ff(d, a, b, c, x[i+13], 7 );
    c = md4_ff(c, d, a, b, x[i+14], 11);
    b = md4_ff(b, c, d, a, x[i+15], 19);

    a = md4_gg(a, b, c, d, x[i+ 0], 3 );
    d = md4_gg(d, a, b, c, x[i+ 4], 5 );
    c = md4_gg(c, d, a, b, x[i+ 8], 9 );
    b = md4_gg(b, c, d, a, x[i+12], 13);
    a = md4_gg(a, b, c, d, x[i+ 1], 3 );
    d = md4_gg(d, a, b, c, x[i+ 5], 5 );
    c = md4_gg(c, d, a, b, x[i+ 9], 9 );
    b = md4_gg(b, c, d, a, x[i+13], 13);
    a = md4_gg(a, b, c, d, x[i+ 2], 3 );
    d = md4_gg(d, a, b, c, x[i+ 6], 5 );
    c = md4_gg(c, d, a, b, x[i+10], 9 );
    b = md4_gg(b, c, d, a, x[i+14], 13);
    a = md4_gg(a, b, c, d, x[i+ 3], 3 );
    d = md4_gg(d, a, b, c, x[i+ 7], 5 );
    c = md4_gg(c, d, a, b, x[i+11], 9 );
    b = md4_gg(b, c, d, a, x[i+15], 13);

    a = md4_hh(a, b, c, d, x[i+ 0], 3 );
    d = md4_hh(d, a, b, c, x[i+ 8], 9 );
    c = md4_hh(c, d, a, b, x[i+ 4], 11);
    b = md4_hh(b, c, d, a, x[i+12], 15);
    a = md4_hh(a, b, c, d, x[i+ 2], 3 );
    d = md4_hh(d, a, b, c, x[i+10], 9 );
    c = md4_hh(c, d, a, b, x[i+ 6], 11);
    b = md4_hh(b, c, d, a, x[i+14], 15);
    a = md4_hh(a, b, c, d, x[i+ 1], 3 );
    d = md4_hh(d, a, b, c, x[i+ 9], 9 );
    c = md4_hh(c, d, a, b, x[i+ 5], 11);
    b = md4_hh(b, c, d, a, x[i+13], 15);
    a = md4_hh(a, b, c, d, x[i+ 3], 3 );
    d = md4_hh(d, a, b, c, x[i+11], 9 );
    c = md4_hh(c, d, a, b, x[i+ 7], 11);
    b = md4_hh(b, c, d, a, x[i+15], 15);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);

  }
  return Array(a, b, c, d);

}

function md4_cmn(q, a, b, x, s, t)
{
  return safe_add(rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md4_ff(a, b, c, d, x, s)
{
  return md4_cmn((b & c) | ((~b) & d), a, 0, x, s, 0);
}
function md4_gg(a, b, c, d, x, s)
{
  return md4_cmn((b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249);
}
function md4_hh(a, b, c, d, x, s)
{
  return md4_cmn(b ^ c ^ d, a, 0, x, s, 1859775393);
}

/*
 * Calculate the HMAC-MD4, of a key and some data
 */
function core_hmac_md4(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md4(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md4(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md4(opad.concat(hash), 512 + 128);
}

function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

    </script>
    <form>
      <font color=#000000 size=3>Input</font>  </td><td > <input type=text name=input size=40><br>
      <font color=#000000 size=3>Result</font> </td><td > <input type=text name=hash size=40><br>
      <input type=button value="MD4 It!" onclick="hash.value = hex_md4(input.value)">
    </form>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <!--
      CryptoMX Tools
      Copyright (C) 2004 - 2006 Derek Buitenhuis

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation; either version 2
      of the License, or (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -->
    <title>ASCII/Binary Converter</title>
  </head>
  <body text="black" link="blue" vlink="blue" alink="red"><br><br>
    <script language="JavaScript1.2">
function dobin(text,sepa) {
var letbin = ""
for (i=0; i<text.length;i++) {

let = text.substr(i,1);
if (i>0) {
var sep = sepa;
if (i % 10 == 0) {
  letbin=letbin+''
}
}
else {
var sep = "";
}

//Ascii -- Binary Code
if (let ==  "A") {letbin = letbin + sep + '01000001'}
if (let ==  "B") {letbin = letbin + sep + '01000010'}
if (let ==  "C") {letbin = letbin + sep + '01000011'}
if (let ==  "D") {letbin = letbin + sep + '01000100'}
if (let ==  "E") {letbin = letbin + sep + '01000101'}
if (let ==  "F") {letbin = letbin + sep + '01000110'}
if (let ==  "G") {letbin = letbin + sep + '01000111'}
if (let ==  "H") {letbin = letbin + sep + '01001000'}
if (let ==  "I") {letbin = letbin + sep + '01001001'}
if (let ==  "J") {letbin = letbin + sep + '01001010'}
if (let ==  "K") {letbin = letbin + sep + '01001011'}
if (let ==  "L") {letbin = letbin + sep + '01001100'}
if (let ==  "M") {letbin = letbin + sep + '01001101'}
if (let ==  "N") {letbin = letbin + sep + '01001110'}
if (let ==  "O") {letbin = letbin + sep + '01001111'}
if (let ==  "P") {letbin = letbin + sep + '01010000'}
if (let ==  "Q") {letbin = letbin + sep + '01010001'}
if (let ==  "R") {letbin = letbin + sep + '01010010'}
if (let ==  "S") {letbin = letbin + sep + '01010011'}
if (let ==  "T") {letbin = letbin + sep + '01010100'}
if (let ==  "U") {letbin = letbin + sep + '01010101'}
if (let ==  "V") {letbin = letbin + sep + '01010110'}
if (let ==  "W") {letbin = letbin + sep + '01010111'}
if (let ==  "X") {letbin = letbin + sep + '01011000'}
if (let ==  "Y") {letbin = letbin + sep + '01011001'}
if (let ==  "Z") {letbin = letbin + sep + '01011010'}
if (let ==  "a") {letbin = letbin + sep + '01100001'}
if (let ==  "b") {letbin = letbin + sep + '01100010'}
if (let ==  "c") {letbin = letbin + sep + '01100011'}
if (let ==  "d") {letbin = letbin + sep + '01100100'}
if (let ==  "e") {letbin = letbin + sep + '01100101'}
if (let ==  "f") {letbin = letbin + sep + '01100110'}
if (let ==  "g") {letbin = letbin + sep + '01100111'}
if (let ==  "h") {letbin = letbin + sep + '01101000'}
if (let ==  "i") {letbin = letbin + sep + '01101001'}
if (let ==  "j") {letbin = letbin + sep + '01101010'}
if (let ==  "k") {letbin = letbin + sep + '01101011'}
if (let ==  "l") {letbin = letbin + sep + '01101100'}
if (let ==  "m") {letbin = letbin + sep + '01101101'}
if (let ==  "n") {letbin = letbin + sep + '01101110'}
if (let ==  "o") {letbin = letbin + sep + '01101111'}
if (let ==  "p") {letbin = letbin + sep + '01110000'}
if (let ==  "q") {letbin = letbin + sep + '01110001'}
if (let ==  "r") {letbin = letbin + sep + '01110010'}
if (let ==  "s") {letbin = letbin + sep + '01110011'}
if (let ==  "t") {letbin = letbin + sep + '01110100'}
if (let ==  "u") {letbin = letbin + sep + '01110101'}
if (let ==  "v") {letbin = letbin + sep + '01110110'}
if (let ==  "w") {letbin = letbin + sep + '01110111'}
if (let ==  "x") {letbin = letbin + sep + '01111000'}
if (let ==  "y") {letbin = letbin + sep + '01111001'}
if (let ==  "z") {letbin = letbin + sep + '01111010'}
if (let ==  " ") {letbin = letbin + sep + '00100000'}

//Numbers:
if (let ==  "0") {letbin = letbin + sep + '00110000'}
if (let ==  "1") {letbin = letbin + sep + '00110001'}
if (let ==  "2") {letbin = letbin + sep + '00110010'}
if (let ==  "3") {letbin = letbin + sep + '00110011'}
if (let ==  "4") {letbin = letbin + sep + '00110100'}
if (let ==  "5") {letbin = letbin + sep + '00110101'}
if (let ==  "6") {letbin = letbin + sep + '00110110'}
if (let ==  "7") {letbin = letbin + sep + '00110111'}
if (let ==  "8") {letbin = letbin + sep + '00111000'}
if (let ==  "9") {letbin = letbin + sep + '00111001'}

//Special Characters:
if (let ==  "!") {letbin = letbin + sep + '00100001'}
if (let ==  "\"") {letbin = letbin + sep + '00100010'}
if (let ==  "#") {letbin = letbin + sep + '00100011'}
if (let ==  "$") {letbin = letbin + sep + '00100100'}
if (let ==  "%") {letbin = letbin + sep + '00100101'}
if (let ==  "&") {letbin = letbin + sep + '00100110'}
if (let ==  "'") {letbin = letbin + sep + '00100111'}
if (let ==  "(") {letbin = letbin + sep + '00101000'}
if (let ==  ")") {letbin = letbin + sep + '00101001'}
if (let ==  "*") {letbin = letbin + sep + '00101001'}
if (let ==  "+") {letbin = letbin + sep + '00101011'}
if (let ==  ",") {letbin = letbin + sep + '00101100'}
if (let ==  "-") {letbin = letbin + sep + '00101101'}
if (let ==  ".") {letbin = letbin + sep + '00101110'}
if (let ==  "/") {letbin = letbin + sep + '00101111'}
if (let ==  ":") {letbin = letbin + sep + '00111010'}
if (let ==  ";") {letbin = letbin + sep + '00111011'}
if (let ==  "<") {letbin = letbin + sep + '00111100'}
if (let ==  "=") {letbin = letbin + sep + '00111101'}
if (let ==  ">") {letbin = letbin + sep + '00111110'}
if (let ==  "?") {letbin = letbin + sep + '00111111'}
if (let ==  "@") {letbin = letbin + sep + '01000000'}
if (let ==  "[") {letbin = letbin + sep + '01011011'}
if (let ==  "\\") {letbin = letbin + sep + '01011100'}
if (let ==  "]") {letbin = letbin + sep + '01011101'}
if (let ==  "^") {letbin = letbin + sep + '01011110'}
if (let ==  "_") {letbin = letbin + sep + '01011111'}
if (let ==  "`") {letbin = letbin + sep + '01100000'}
if (let ==  "{") {letbin = letbin + sep + '01111011'}
if (let ==  "|") {letbin = letbin + sep + '01111100'}
if (let ==  "}") {letbin = letbin + sep + '01111101'}
if (let ==  "~") {letbin = letbin + sep + '01111110'}
if (let ==  "�") {letbin = letbin + sep + '10000000'}
if (let ==  "¡") {letbin = letbin + sep + '10100001'}
if (let ==  "¢") {letbin = letbin + sep + '10100010'}
if (let ==  "£") {letbin = letbin + sep + '10100011'}
if (let ==  "�") {letbin = letbin + sep + '10100100'}
if (let ==  "�") {letbin = letbin + sep + '10100101'}
if (let ==  "�") {letbin = letbin + sep + '10100110'}
if (let ==  "§") {letbin = letbin + sep + '10100111'}
if (let ==  "�") {letbin = letbin + sep + '10100111'}
if (let ==  "�") {letbin = letbin + sep + '10101001'}
if (let ==  "�") {letbin = letbin + sep + '10101010'}
if (let ==  "«") {letbin = letbin + sep + '10101011'}
if (let ==  "�") {letbin = letbin + sep + '10101100'}
if (let ==  "�") {letbin = letbin + sep + '10101101'}
if (let ==  "�") {letbin = letbin + sep + '10101110'}
if (let ==  "�") {letbin = letbin + sep + '10101111'}
if (let ==  "�") {letbin = letbin + sep + '10110000'}
if (let ==  "�") {letbin = letbin + sep + '10110001'}
if (let ==  "�") {letbin = letbin + sep + '10110010'}
if (let ==  "�") {letbin = letbin + sep + '10110011'}
if (let ==  "�") {letbin = letbin + sep + '10110100'}
if (let ==  "�") {letbin = letbin + sep + '10110101'}
if (let ==  "�") {letbin = letbin + sep + '10110110'}
if (let ==  "�") {letbin = letbin + sep + '10110111'}
if (let ==  "�") {letbin = letbin + sep + '10111000'}
if (let ==  "�") {letbin = letbin + sep + '10111001'}
if (let ==  "�") {letbin = letbin + sep + '10111010'}
if (let ==  "»") {letbin = letbin + sep + '10111011'}
if (let ==  "�") {letbin = letbin + sep + '10111100'}
if (let ==  "�") {letbin = letbin + sep + '10111101'}
if (let ==  "�") {letbin = letbin + sep + '10111110'}
if (let ==  "�") {letbin = letbin + sep + '10111111'}
if (let ==  "�") {letbin = letbin + sep + '11000000'}
if (let ==  "�") {letbin = letbin + sep + '11000001'}
if (let ==  "�") {letbin = letbin + sep + '11000010'}
if (let ==  "�") {letbin = letbin + sep + '11000011'}
if (let ==  "Ä") {letbin = letbin + sep + '11000100'}
if (let ==  "Å") {letbin = letbin + sep + '11000101'}
if (let ==  "Æ") {letbin = letbin + sep + '11000110'}
if (let ==  "Ç") {letbin = letbin + sep + '11000111'}
if (let ==  "�") {letbin = letbin + sep + '11001000'}
if (let ==  "�") {letbin = letbin + sep + '11001001'}
if (let ==  "�") {letbin = letbin + sep + '11001010'}
if (let ==  "Ë") {letbin = letbin + sep + '11001011'}
if (let ==  "�") {letbin = letbin + sep + '11001100'}
if (let ==  "�") {letbin = letbin + sep + '11001101'}
if (let ==  "�") {letbin = letbin + sep + '11001110'}
if (let ==  "�") {letbin = letbin + sep + '11001111'}
if (let ==  "�") {letbin = letbin + sep + '11010000'}
if (let ==  "�") {letbin = letbin + sep + '11010001'}
if (let ==  "�") {letbin = letbin + sep + '11010010'}
if (let ==  "�") {letbin = letbin + sep + '11010011'}
if (let ==  "�") {letbin = letbin + sep + '11010100'}
if (let ==  "�") {letbin = letbin + sep + '11010101'}
if (let ==  "Ö") {letbin = letbin + sep + '11010110'}
if (let ==  "�") {letbin = letbin + sep + '11010111'}
if (let ==  "Ø") {letbin = letbin + sep + '11011000'}
if (let ==  "�") {letbin = letbin + sep + '11011001'}
if (let ==  "�") {letbin = letbin + sep + '11011010'}
if (let ==  "�") {letbin = letbin + sep + '11011011'}
if (let ==  "Ü") {letbin = letbin + sep + '11011100'}
if (let ==  "�") {letbin = letbin + sep + '11011101'}
if (let ==  "�") {letbin = letbin + sep + '11011110'}
if (let ==  "ß") {letbin = letbin + sep + '11011111'}
if (let ==  "à") {letbin = letbin + sep + '11100000'}
if (let ==  "á") {letbin = letbin + sep + '11100001'}
if (let ==  "â") {letbin = letbin + sep + '11100010'}
if (let ==  "�") {letbin = letbin + sep + '11100011'}
if (let ==  "ä") {letbin = letbin + sep + '11100100'}
if (let ==  "å") {letbin = letbin + sep + '11100101'}
if (let ==  "æ") {letbin = letbin + sep + '11100110'}
if (let ==  "ç") {letbin = letbin + sep + '11100111'}
if (let ==  "è") {letbin = letbin + sep + '11101000'}
if (let ==  "é") {letbin = letbin + sep + '11101001'}
if (let ==  "ê") {letbin = letbin + sep + '11101010'}
if (let ==  "ë") {letbin = letbin + sep + '11101011'}
if (let ==  "ì") {letbin = letbin + sep + '11101100'}
if (let ==  "í") {letbin = letbin + sep + '11101101'}
if (let ==  "î") {letbin = letbin + sep + '11101110'}
if (let ==  "�") {letbin = letbin + sep + '11101111'}
if (let ==  "�") {letbin = letbin + sep + '11110000'}
if (let ==  "ñ") {letbin = letbin + sep + '11110001'}
if (let ==  "ò") {letbin = letbin + sep + '11110010'}
if (let ==  "ó") {letbin = letbin + sep + '11110011'}
if (let ==  "ô") {letbin = letbin + sep + '11110100'}
if (let ==  "�") {letbin = letbin + sep + '11110101'}
if (let ==  "ö") {letbin = letbin + sep + '11110110'}
if (let ==  "�") {letbin = letbin + sep + '11110111'}
if (let ==  "ø") {letbin = letbin + sep + '11111000'}
if (let ==  "ù") {letbin = letbin + sep + '11111001'}
if (let ==  "ú") {letbin = letbin + sep + '11111010'}
if (let ==  "û") {letbin = letbin + sep + '11111011'}
if (let ==  "û") {letbin = letbin + sep + '11111100'}
if (let ==  "�") {letbin = letbin + sep + '11111101'}
if (let ==  "�") {letbin = letbin + sep + '11111110'}
if (let ==  "�") {letbin = letbin + sep + '11111111'}

}
document.asc2bin.binary.value = letbin
return false;
}

function doasc(text) {

if (text.length % 8 != 0) {
  alert (text + " is not an even binary.\n\nYou may have missed a digit or maybe added an additional digit/character.\n\nSeparaters are NOT required here.")
  return false;
  last;
}
var letasc = ""
lettot = text.length / 8
j=0
for (i=0; i<lettot;i++) {

let = text.substr(j,8);



if (let ==  "01000001") {letasc = letasc + 'A'}
if (let ==  "01000010") {letasc = letasc + 'B'}
if (let ==  "01000011") {letasc = letasc + 'C'}
if (let ==  "01000100") {letasc = letasc + 'D'}
if (let ==  "01000101") {letasc = letasc + 'E'}
if (let ==  "01000110") {letasc = letasc + 'F'}
if (let ==  "01000111") {letasc = letasc + 'G'}
if (let ==  "01001000") {letasc = letasc + 'H'}
if (let ==  "01001001") {letasc = letasc + 'I'}
if (let ==  "01001010") {letasc = letasc + 'J'}
if (let ==  "01001011") {letasc = letasc + 'K'}
if (let ==  "01001100") {letasc = letasc + 'L'}
if (let ==  "01001101") {letasc = letasc + 'M'}
if (let ==  "01001110") {letasc = letasc + 'N'}
if (let ==  "01001111") {letasc = letasc + 'O'}
if (let ==  "01010000") {letasc = letasc + 'P'}
if (let ==  "01010001") {letasc = letasc + 'Q'}
if (let ==  "01010010") {letasc = letasc + 'R'}
if (let ==  "01010011") {letasc = letasc + 'S'}
if (let ==  "01010100") {letasc = letasc + 'T'}
if (let ==  "01010101") {letasc = letasc + 'U'}
if (let ==  "01010110") {letasc = letasc + 'V'}
if (let ==  "01010111") {letasc = letasc + 'W'}
if (let ==  "01011000") {letasc = letasc + 'X'}
if (let ==  "01011001") {letasc = letasc + 'Y'}
if (let ==  "01011010") {letasc = letasc + 'Z'}
if (let ==  "01100001") {letasc = letasc + 'a'}
if (let ==  "01100010") {letasc = letasc + 'b'}
if (let ==  "01100011") {letasc = letasc + 'c'}
if (let ==  "01100100") {letasc = letasc + 'd'}
if (let ==  "01100101") {letasc = letasc + 'e'}
if (let ==  "01100110") {letasc = letasc + 'f'}
if (let ==  "01100111") {letasc = letasc + 'g'}
if (let ==  "01101000") {letasc = letasc + 'h'}
if (let ==  "01101001") {letasc = letasc + 'i'}
if (let ==  "01101010") {letasc = letasc + 'j'}
if (let ==  "01101011") {letasc = letasc + 'k'}
if (let ==  "01101100") {letasc = letasc + 'l'}
if (let ==  "01101101") {letasc = letasc + 'm'}
if (let ==  "01101110") {letasc = letasc + 'n'}
if (let ==  "01101111") {letasc = letasc + 'o'}
if (let ==  "01110000") {letasc = letasc + 'p'}
if (let ==  "01110001") {letasc = letasc + 'q'}
if (let ==  "01110010") {letasc = letasc + 'r'}
if (let ==  "01110011") {letasc = letasc + 's'}
if (let ==  "01110100") {letasc = letasc + 't'}
if (let ==  "01110101") {letasc = letasc + 'u'}
if (let ==  "01110110") {letasc = letasc + 'v'}
if (let ==  "01110111") {letasc = letasc + 'w'}
if (let ==  "01111000") {letasc = letasc + 'x'}
if (let ==  "01111001") {letasc = letasc + 'y'}
if (let ==  "01111010") {letasc = letasc + 'z'}
if (let ==  "00100000") {letasc = letasc + ' '}

//Numbers:
if (let ==  "00110000") {letasc = letasc + '0'}
if (let ==  "00110001") {letasc = letasc + '1'}
if (let ==  "00110010") {letasc = letasc + '2'}
if (let ==  "00110011") {letasc = letasc + '3'}
if (let ==  "00110100") {letasc = letasc + '4'}
if (let ==  "00110101") {letasc = letasc + '5'}
if (let ==  "00110110") {letasc = letasc + '6'}
if (let ==  "00110111") {letasc = letasc + '7'}
if (let ==  "00111000") {letasc = letasc + '8'}
if (let ==  "00111001") {letasc = letasc + '9'}

//Special Characters:
if (let ==  "00100001") {letasc = letasc + '!'}
if (let ==  "00100010") {letasc = letasc + '\"'}
if (let ==  "00100011") {letasc = letasc + '#'}
if (let ==  "00100100") {letasc = letasc + '$'}
if (let ==  "00100101") {letasc = letasc + '%'}
if (let ==  "00100110") {letasc = letasc + '&'}
if (let ==  "00100111") {letasc = letasc + '\''}
if (let ==  "00101000") {letasc = letasc + '('}
if (let ==  "00101001") {letasc = letasc + ')'}
if (let ==  "00101001") {letasc = letasc + '*'}
if (let ==  "00101011") {letasc = letasc + '+'}
if (let ==  "00101100") {letasc = letasc + ','}
if (let ==  "00101101") {letasc = letasc + '-'}
if (let ==  "00101110") {letasc = letasc + '.'}
if (let ==  "00101111") {letasc = letasc + '/'}
if (let ==  "00111010") {letasc = letasc + ':'}
if (let ==  "00111011") {letasc = letasc + ';'}
if (let ==  "00111100") {letasc = letasc + '<'}
if (let ==  "00111101") {letasc = letasc + '='}
if (let ==  "00111110") {letasc = letasc + '>'}
if (let ==  "00111111") {letasc = letasc + '?'}
if (let ==  "01000000") {letasc = letasc + '@'}
if (let ==  "01011011") {letasc = letasc + '['}
if (let ==  "01011100") {letasc = letasc + '\\'}
if (let ==  "01011101") {letasc = letasc + ']'}
if (let ==  "01011110") {letasc = letasc + '^'}
if (let ==  "01011111") {letasc = letasc + '_'}
if (let ==  "01100000") {letasc = letasc + '`'}
if (let ==  "01111011") {letasc = letasc + '{'}
if (let ==  "01111100") {letasc = letasc + '|'}
if (let ==  "01111101") {letasc = letasc + '}'}
if (let ==  "01111110") {letasc = letasc + '~'}
if (let ==  "10000000") {letasc = letasc + '�'}
if (let ==  "10100001") {letasc = letasc + '¡'}
if (let ==  "10100010") {letasc = letasc + '¢'}
if (let ==  "10100011") {letasc = letasc + '£'}
if (let ==  "10100100") {letasc = letasc + '�'}
if (let ==  "10100101") {letasc = letasc + '�'}
if (let ==  "10100110") {letasc = letasc + '�'}
if (let ==  "10100111") {letasc = letasc + '§'}
if (let ==  "10100111") {letasc = letasc + '�'}
if (let ==  "10101001") {letasc = letasc + '�'}
if (let ==  "10101010") {letasc = letasc + '�'}
if (let ==  "10101011") {letasc = letasc + '«'}
if (let ==  "10101100") {letasc = letasc + '�'}
if (let ==  "10101101") {letasc = letasc + '�'}
if (let ==  "10101110") {letasc = letasc + '�'}
if (let ==  "10101111") {letasc = letasc + '�'}
if (let ==  "10110000") {letasc = letasc + '�'}
if (let ==  "10110001") {letasc = letasc + '�'}
if (let ==  "10110010") {letasc = letasc + '�'}
if (let ==  "10110011") {letasc = letasc + '�'}
if (let ==  "10110100") {letasc = letasc + '�'}
if (let ==  "10110101") {letasc = letasc + '�'}
if (let ==  "10110110") {letasc = letasc + '�'}
if (let ==  "10110111") {letasc = letasc + '�'}
if (let ==  "10111000") {letasc = letasc + '�'}
if (let ==  "10111001") {letasc = letasc + '�'}
if (let ==  "10111010") {letasc = letasc + '�'}
if (let ==  "10111011") {letasc = letasc + '»'}
if (let ==  "10111100") {letasc = letasc + '�'}
if (let ==  "10111101") {letasc = letasc + '�'}
if (let ==  "10111110") {letasc = letasc + '�'}
if (let ==  "10111111") {letasc = letasc + '�'}
if (let ==  "11000000") {letasc = letasc + '�'}
if (let ==  "11000001") {letasc = letasc + '�'}
if (let ==  "11000010") {letasc = letasc + '�'}
if (let ==  "11000011") {letasc = letasc + '�'}
if (let ==  "11000100") {letasc = letasc + 'Ä'}
if (let ==  "11000101") {letasc = letasc + 'Å'}
if (let ==  "11000110") {letasc = letasc + 'Æ'}
if (let ==  "11000111") {letasc = letasc + 'Ç'}
if (let ==  "11001000") {letasc = letasc + '�'}
if (let ==  "11001001") {letasc = letasc + '�'}
if (let ==  "11001010") {letasc = letasc + '�'}
if (let ==  "11001011") {letasc = letasc + 'Ë'}
if (let ==  "11001100") {letasc = letasc + '�'}
if (let ==  "11001101") {letasc = letasc + '�'}
if (let ==  "11001110") {letasc = letasc + '�'}
if (let ==  "11001111") {letasc = letasc + '�'}
if (let ==  "11010000") {letasc = letasc + '�'}
if (let ==  "11010001") {letasc = letasc + '�'}
if (let ==  "11010010") {letasc = letasc + '�'}
if (let ==  "11010011") {letasc = letasc + '�'}
if (let ==  "11010100") {letasc = letasc + '�'}
if (let ==  "11010101") {letasc = letasc + '�'}
if (let ==  "11010110") {letasc = letasc + 'Ö'}
if (let ==  "11010111") {letasc = letasc + '�'}
if (let ==  "11011000") {letasc = letasc + 'Ø'}
if (let ==  "11011001") {letasc = letasc + '�'}
if (let ==  "11011010") {letasc = letasc + '�'}
if (let ==  "11011011") {letasc = letasc + '�'}
if (let ==  "11011100") {letasc = letasc + 'Ü'}
if (let ==  "11011101") {letasc = letasc + '�'}
if (let ==  "11011110") {letasc = letasc + '�'}
if (let ==  "11011111") {letasc = letasc + 'ß'}
if (let ==  "11100000") {letasc = letasc + 'à'}
if (let ==  "11100001") {letasc = letasc + 'á'}
if (let ==  "11100010") {letasc = letasc + 'â'}
if (let ==  "11100011") {letasc = letasc + '�'}
if (let ==  "11100100") {letasc = letasc + 'ä'}
if (let ==  "11100101") {letasc = letasc + 'å'}
if (let ==  "11100110") {letasc = letasc + 'æ'}
if (let ==  "11100111") {letasc = letasc + 'ç'}
if (let ==  "11101000") {letasc = letasc + 'è'}
if (let ==  "11101001") {letasc = letasc + 'é'}
if (let ==  "11101010") {letasc = letasc + 'ê'}
if (let ==  "11101011") {letasc = letasc + 'ë'}
if (let ==  "11101100") {letasc = letasc + 'ì'}
if (let ==  "11101101") {letasc = letasc + 'í'}
if (let ==  "11101110") {letasc = letasc + 'î'}
if (let ==  "11101111") {letasc = letasc + '�'}
if (let ==  "11110000") {letasc = letasc + '�'}
if (let ==  "11110001") {letasc = letasc + 'ñ'}
if (let ==  "11110010") {letasc = letasc + 'ò'}
if (let ==  "11110011") {letasc = letasc + 'ó'}
if (let ==  "11110100") {letasc = letasc + 'ô'}
if (let ==  "11110101") {letasc = letasc + '�'}
if (let ==  "11110110") {letasc = letasc + 'ö'}
if (let ==  "11110111") {letasc = letasc + '�'}
if (let ==  "11111000") {letasc = letasc + 'ø'}
if (let ==  "11111001") {letasc = letasc + 'ù'}
if (let ==  "11111010") {letasc = letasc + 'ú'}
if (let ==  "11111011") {letasc = letasc + 'û'}
if (let ==  "11111100") {letasc = letasc + 'û'}
if (let ==  "11111101") {letasc = letasc + '�'}
if (let ==  "11111110") {letasc = letasc + '�'}
if (let ==  "11111111") {letasc = letasc + '�'}
if (letasc == "") {
  alert ("not found")
  break;
}
j=j+8
}
document.bin2asc.ascii.value = letasc
return false;
}
    </script>
    <form name="asc2bin">
      <strong>Convert to Binary</strong><br>
      Enter Text: <input type="Text" name="text" size="92"><br>
      <input type="hidden" name="separater" maxlength="1" size="1">
      <input type="button" value="Convert" onclick="dobin(document.asc2bin.text.value,document.asc2bin.separater.value);">
      <br><br>
      Binary Output: <input type="Text" name="binary" size="90">
    </form>
    <br><br>
    <form name="bin2asc">
      <strong>Convert to Ascii</strong><br>
      Enter Binary: <input type="Text" name="text" size="90"><br>
      <input type="button" value="Convert" onclick="doasc(document.bin2asc.text.value);">
      <br><br>
      ASCII Output: <input type="Text" name="ascii" size="90">
    </form>
    <br><br>
  </body>
</html>
         
Posted by 1010
반응형
<html>
  <head>
    <!--
      CryptoMX Tools
      Copyright (C) 2004 - 2006 Derek Buitenhuis

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation; either version 2
      of the License, or (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    -->
    <title>Base64 Encoding/Decoding</title>
  </head>
  <body>
   <script type="text/javascript"><!--

   var keyStr = "ABCDEFGHIJKLMNOP" +
                "QRSTUVWXYZabcdef" +
                "ghijklmnopqrstuv" +
                "wxyz0123456789+/" +
                "=";

   function encode64(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      do {
         chr1 = input.charCodeAt(i++);
         chr2 = input.charCodeAt(i++);
         chr3 = input.charCodeAt(i++);

         enc1 = chr1 >> 2;
         enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
         enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
         enc4 = chr3 & 63;

         if (isNaN(chr2)) {
            enc3 = enc4 = 64;
         } else if (isNaN(chr3)) {
            enc4 = 64;
         }

         output = output +
            keyStr.charAt(enc1) +
            keyStr.charAt(enc2) +
            keyStr.charAt(enc3) +
            keyStr.charAt(enc4);
         chr1 = chr2 = chr3 = "";
         enc1 = enc2 = enc3 = enc4 = "";
      } while (i < input.length);

      return output;
   }

   function decode64(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
      var base64test = /[^A-Za-z0-9\+\/\=]/g;
      if (base64test.exec(input)) {
         alert("There were invalid base64 characters in the input text.\n" +
               "Valid base64 characters are A-Z, a-z, 0-9, �+�, �/�, and �=�\n" +
               "Expect errors in decoding.");
      }
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

      do {
         enc1 = keyStr.indexOf(input.charAt(i++));
         enc2 = keyStr.indexOf(input.charAt(i++));
         enc3 = keyStr.indexOf(input.charAt(i++));
         enc4 = keyStr.indexOf(input.charAt(i++));

         chr1 = (enc1 << 2) | (enc2 >> 4);
         chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
         chr3 = ((enc3 & 3) << 6) | enc4;

         output = output + String.fromCharCode(chr1);

         if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
         }
         if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
         }

         chr1 = chr2 = chr3 = "";
         enc1 = enc2 = enc3 = enc4 = "";

      } while (i < input.length);

      return output;
   }

   //--></script>
    <form name="base64Form">
      <center>
        Type in the message you want to encode in Base64, or paste<br>
        Base64 encoded text into the text field, select Encode or Decode, <br>
        and click the button! You can use Base64 encoded messages with<br>
        the <a href="stegano.html">Steganography</a> page.<br>
        <br>
        <textarea name="theText" cols="40" rows="6"></textarea><br>
        <input type="button" name="encode" value="Encode to base64"
          onClick="document.base64Form.theText.value=encode64(document.base64Form.theText.value);">
        <input type="button" name="decode" value="Decode from base64"
          onClick="document.base64Form.theText.value=decode64(document.base64Form.theText.value);">
      <center>
    </form>
  </body>
</html>
           

Posted by 1010
반응형
<HTML>
<HEAD>
<TITLE>TextRange.compareEndPoints() Method</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var fixedRange
function setAndShowRangeData() {
    var selectedRange = document.selection.createRange()
    var result1 = fixedRange.compareEndPoints("StartToEnd", selectedRange)
    var result2 = fixedRange.compareEndPoints("StartToStart", selectedRange)
    var result3 = fixedRange.compareEndPoints("EndToStart", selectedRange)
    var result4 = fixedRange.compareEndPoints("EndToEnd", selectedRange)
   
    B1.innerText = result1
    compare1.innerText = getDescription(result1)
    B2.innerText = result2
    compare2.innerText = getDescription(result2)
    B3.innerText = result3
    compare3.innerText = getDescription(result3)
    B4.innerText = result4
    compare4.innerText = getDescription(result4)
}
function getDescription(comparisonValue) {
    switch (comparisonValue) {
        case -1 :
            return "comes before"
            break
        case 0 :
            return "is the same as"
            break
        case 1 :
            return "comes after"
            break
        default :
            return "vs."    
    }
}
function init() {
    fixedRange = document.body.createTextRange()
    fixedRange.moveToElementText(fixedRangeElem)
}
</SCRIPT>
</HEAD>
<BODY onLoad="init()">
<H1>TextRange.compareEndPoints() Method</H1>
<HR>
<P>Select text in the paragraph in various places relative to
the fixed text range (shown in red).</P>
<TABLE ID="results" BORDER=1 >
<TR><TH>Property</TH><TH>Returned Value</TH><TH>Fixed Range vs. Selection</TR>
<TR>
    <TD CLASS="propName">StartToEnd</TD>
    <TD CLASS="count" ID="B1">&nbsp;</TD>
    <TD CLASS="count" ID="C1">Start of Fixed
    <SPAN ID="compare1">vs.</SPAN> End of Selection</TD>
</TR>
<TR>
    <TD CLASS="propName">StartToStart</TD>
    <TD CLASS="count" ID="B2">&nbsp;</TD>

<TD CLASS="count" ID="C2">Start of Fixed
    <SPAN ID="compare2">vs.</SPAN> Start of Selection</TD>
</TR>
<TR>
    <TD CLASS="propName">EndToStart</TD>
    <TD CLASS="count" ID="B3">&nbsp;</TD>
    <TD CLASS="count" ID="C3">End of Fixed
    <SPAN ID="compare3">vs.</SPAN> Start of Selection</TD>
</TR>
<TR>
    <TD CLASS="propName">EndToEnd</TD>
    <TD CLASS="count" ID="B4">&nbsp;</TD>
    <TD CLASS="count" ID="C4">End of Fixed
    <SPAN ID="compare4">vs.</SPAN> End of Selection</TD>
</TR>
</TABLE>
<HR>
<P onMouseUp="setAndShowRangeData()">
Text, Text,Text,Text,Text,Text,Text,Text,Text,Text,<SPAN ID="fixedRangeElem">
Text,Text,Text,Text,Text,Text,Text,Text,</SPAN>,
Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,</P>
</BODY>
</HTML>

Posted by 1010
반응형
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
     Example File From "JavaScript and DHTML Cookbook"
     Published by O'Reilly & Associates
     Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipe 14.7</title>
<link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" />
<style type="text/css">
table {table-collapse:collapse; border-spacing:0}
td {border:2px groove black; padding:7px; background-color:#ccffcc}
th {border:2px groove black; padding:7px; background-color:#ffffcc}
.ctr {text-align:center}
</style>
<script type="text/javascript">
// Table data -- an array of objects
var jsData = new Array();
jsData[0] = {location:"Uruguay", year:1930, winner:"Uruguay", winScore:4,
             loser:"Argentina", losScore:2};
jsData[1] = {location:"Italy", year:1934, winner:"Italy", winScore:2,
             loser:"Czechoslovakia", losScore:1};
jsData[2] = {location:"France", year:1938, winner:"Italy", winScore:4,
             loser:"Hungary", losScore:2};
jsData[3] = {location:"Brazil", year:1950, winner:"Uruguay", winScore:2,
             loser:"Brazil", losScore:1};
jsData[4] = {location:"Switzerland", year:1954, winner:"West Germany", winScore:3,
             loser:"Hungary", losScore:2};

// Draw table from 'jsData' array of objects
function drawTable(tbody) {
    var tr, td;
    tbody = document.getElementById(tbody);
    // loop through data source
    for (var i = 0; i < jsData.length; i++) {
        tr = tbody.insertRow(tbody.rows.length);
        td = tr.insertCell(tr.cells.length);
        td.setAttribute("align", "center");
        td.innerHTML = jsData[i].year;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsData[i].location;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsData[i].winner;
        td = tr.insertCell(tr.cells.length);
        td.innerHTML = jsData[i].loser;
        td = tr.insertCell(tr.cells.length);
        td.setAttribute("align", "center");
        td.innerHTML = jsData[i].winScore + " - " + jsData[i].losScore;
    }
}

</script>
</head>
<body onload="drawTable('matchData')">
<h1>Transforming JavaScript Data into HTML Tables</h1>
<hr />

<table id="cupFinals">
<thead>
<tr><th>Year</th>
    <th>Host Country</th>
    <th>Winner</th>
    <th>Loser</th>
    <th>Score (Win - Lose)</th>
</tr>
</thead>
<tbody id="matchData"></tbody>
</table>

</body>
</html>



Posted by 1010
반응형
<head>
<title></title>
</script>
</head>
<body>
<div id="thetable"></div>
<script type = "text/javascript" >
var table = document.createElement("table");
table.border = "1";
var tbody = document.createElement("tbody");

table.appendChild(tbody);
var row = document.createElement("tr");

for (i = 1; i < 3; i++) {
    var row = document.createElement("tr");
    for (j = 1; j < 3; j++) {
        var td = document.createElement("td");
        var data = document.createTextNode("Row " + i + ", Column " + j);
        td.appendChild(data);
        row.appendChild(td);
    }
    tbody.appendChild(row);
}
document.getElementById("thetable").appendChild(table);
</script>
</body>

Posted by 1010
반응형

/*
JavaScript Bible, Fourth Edition
by Danny Goodman

John Wiley & Sons CopyRight 2001
*/

<HTML>
<HEAD>
<TITLE>Modifying Table Cell Content</TITLE>
<STYLE TYPE="text/css">
.absoluteWrap {position:absolute}
.relativeWrap {position:relative}
.total {color:red}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
var Ver4 = parseInt(navigator.appVersion) == 4
var Ver4Up = parseInt(navigator.appVersion) >= 4
var Nav4 = ((navigator.appName == "Netscape") && Ver4)
var modifiable
// calculate and display a row's total
function showTotal(qtyList) {
    var qty = qtyList.options[qtyList.selectedIndex].value
    var prodID = qtyList.name
    var total = "US$" +
        (qty * parseFloat(qtyList.form.elements[prodID + "Price"].value))
    var newCellHTML = "<SPAN CLASS='total'>" + total + "</SPAN>"
    if(Nav4) {
        document.layers[prodID + "TotalWrapper"].document.layers[prodID + 
            "Total"].document.write(newCellHTML)
        document.layers[prodID + "TotalWrapper"].document.layers[prodID + 
            "Total"].document.close()
    } else if (modifiable) {
        if (document.all) {
            document.all(prodID + "Total").innerHTML = newCellHTML
        } else {
            document.getElementById(prodID + "Total").innerHTML = newCellHTML
        }
    }
}
// initialize global flag for browsers capable of modifiable content
function init() {
    modifiable  = (Ver4Up && document.body && document.body.innerHTML)
}
// display content for all products (e.g., in case of Back navigation)
function showAllTotals(form) {
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == "select-one") {       
            showTotal(form.elements[i])
        }        
    }
}
</SCRIPT>
</HEAD>
<BODY onLoad="init(); showAllTotals(document.orderForm)">
<H1>Modifying Table Cell Content</H1>
<HR>
<FORM NAME="orderForm">
<TABLE BORDER=1>
<COLGROUP WIDTH=150>
<COLGROUP WIDTH=100>
<COLGROUP WIDTH=50>
<COLGROUP WIDTH=100
<TR>
    <TH>Product Description</TH>
    <TH>Price Each</TH>
    <TH>Quantity</TH>
    <TH>Total</TH>
</TR>
<TR>
    <TD>Wonder Widget 9000</TD>
    <TD>US$125.00</TD>
    <TD><SELECT NAME="ww9000" onChange="showTotal(this)">
        <OPTION VALUE="0">0
        <OPTION VALUE="1">1
        <OPTION VALUE="2">2
        <OPTION VALUE="3">3
        </SELECT>
        <INPUT TYPE="hidden" NAME="ww9000Price" VALUE="125.00"></TD>
    <TD>
    <SCRIPT LANGUAGE="JavaScript">
    if (Nav4) {

var placeHolder = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
        placeHolder += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
        document.write("<SPAN ID='ww9000TotalWrapper' CLASS='relativeWrap'>")
        document.write("<SPAN ID='ww9000Total' CLASS='absoluteWrap'></SPAN>")
        document.write("<SPAN>" + placeHolder + "</SPAN></SPAN>")
    } else {
        document.write("<SPAN ID='ww9000Total' CLASS='relativeWrap'>" +
          "<P>&nbsp;</P></SPAN>")
    }
    </SCRIPT>
    </TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>


Posted by 1010