15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

グローバル変数を調査する

Posted at

はじめに

javascriptの一つの問題点として、グローバル変数を自由に作れてしまう事があります。
そこで、グローバル変数の存在を確認するスニペットを作ってみました。
変数に代入してもいいし、コンソールに貼付けて実行結果を吐き出しても良いです。
ただし、ブラウザによって標準のグローバル変数が異なるので以下はchromeのversion35.0の例です。
ただ、他のブラウザでも簡単に作れるので後述する方法で各自試してください。

スニペット

/*chromeの場合*/
(function (self) {
  var GLOBALS_ = 'window,Boolean,Number,JSON,DataView,ArrayBuffer,undefined,Proxy,Function,Error,String,Math,WeakSet,eval,Set,document,Intl,Object,Map,URIError,Uint16Array,encodeURI,Array,escape,Int32Array,Int16Array,decodeURI,NaN,Uint8ClampedArray,isNaN,Infinity,external,Promise,parseFloat,Symbol,unescape,WeakMap,RegExp,Uint32Array,ReferenceError,EvalError,Date,RangeError,chrome,top,isFinite,__commandLineAPI,parseInt,SyntaxError,Uint8Array,encodeURIComponent,location,Float64Array,TypeError,decodeURIComponent,Float32Array,Int8Array,speechSynthesis,WebKitSourceBufferList,WebKitSourceBuffer,WebKitMediaSource,XSLTProcessor,VTTCue,TrackEvent,TextTrackList,TextTrackCueList,TextTrackCue,TextTrack,HTMLTrackElement,SpeechSynthesisUtterance,SpeechSynthesisEvent,SharedWorker,MediaKeyEvent,Notification,TimeRanges,MediaError,MediaController,HTMLVideoElement,HTMLSourceElement,HTMLMediaElement,Audio,HTMLAudioElement,MediaSource,FontFace,MediaKeyError,DeviceMotionEvent,webkitSpeechRecognitionEvent,webkitSpeechRecognitionError,webkitSpeechRecognition,webkitSpeechGrammarList,webkitSpeechGrammar,webkitRTCPeerConnection,OfflineAudioContext,AudioContext,webkitOfflineAudioContext,webkitAudioContext,webkitMediaStream,localStorage,sessionStorage,applicationCache,webkitStorageInfo,indexedDB,webkitIndexedDB,crypto,XPathResult,XPathExpression,XPathEvaluator,XMLSerializer,XMLHttpRequestUpload,XMLHttpRequestProgressEvent,XMLHttpRequest,XMLDocument,Worker,Window,WheelEvent,WebSocket,WebKitPoint,WebKitGamepad,WebKitCSSTransformValue,WebKitCSSMatrix,WebKitCSSFilterValue,WebKitCSSFilterRule,WebKitAnimationEvent,WebGLUniformLocation,WebGLTexture,WebGLShaderPrecisionFormat,WebGLShader,WebGLRenderingContext,WebGLRenderbuffer,WebGLProgram,WebGLFramebuffer,WebGLContextEvent,WebGLBuffer,WebGLActiveInfo,ValidityState,URL,UIEvent,TreeWalker,TransitionEvent,TouchList,TouchEvent,Touch,TextMetrics,TextEvent,Text,StyleSheetList,StyleSheet,StorageEvent,Storage,Selection,Screen,SVGZoomEvent,SVGViewSpec,SVGViewElement,SVGUseElement,SVGUnitTypes,SVGTransformList,SVGTransform,SVGTitleElement,SVGTextPositioningElement,SVGTextPathElement,SVGTextElement,SVGTextContentElement,SVGTSpanElement,SVGSymbolElement,SVGSwitchElement,SVGStyleElement,SVGStringList,SVGStopElement,SVGSetElement,SVGScriptElement,SVGSVGElement,SVGRenderingIntent,SVGRectElement,SVGRect,SVGRadialGradientElement,SVGPreserveAspectRatio,SVGPolylineElement,SVGPolygonElement,SVGPointList,SVGPoint,SVGPatternElement,SVGPathSegMovetoRel,SVGPathSegMovetoAbs,SVGPathSegList,SVGPathSegLinetoVerticalRel,SVGPathSegLinetoVerticalAbs,SVGPathSegLinetoRel,SVGPathSegLinetoHorizontalRel,SVGPathSegLinetoHorizontalAbs,SVGPathSegLinetoAbs,SVGPathSegCurvetoQuadraticSmoothRel,SVGPathSegCurvetoQuadraticSmoothAbs,SVGPathSegCurvetoQuadraticRel,SVGPathSegCurvetoQuadraticAbs,SVGPathSegCurvetoCubicSmoothRel,SVGPathSegCurvetoCubicSmoothAbs,SVGPathSegCurvetoCubicRel,SVGPathSegCurvetoCubicAbs,SVGPathSeg,SVGPathSegClosePath,SVGPathSegArcRel,SVGPathSegArcAbs,SVGPathElement,SVGNumberList,SVGNumber,SVGMetadataElement,SVGMatrix,SVGMaskElement,SVGMarkerElement,SVGMPathElement,SVGLinearGradientElement,SVGLineElement,SVGLengthList,SVGLength,SVGImageElement,SVGGraphicsElement,SVGGradientElement,SVGGeometryElement,SVGGElement,SVGForeignObjectElement,SVGFilterElement,SVGFETurbulenceElement,SVGFETileElement,SVGFESpotLightElement,SVGFESpecularLightingElement,SVGFEPointLightElement,SVGFEOffsetElement,SVGFEMorphologyElement,SVGFEMergeNodeElement,SVGFEMergeElement,SVGFEImageElement,SVGFEGaussianBlurElement,SVGFEFuncRElement,SVGFEFuncGElement,SVGFEFuncBElement,SVGFEFuncAElement,SVGFEFloodElement,SVGFEDropShadowElement,SVGFEDistantLightElement,SVGFEDisplacementMapElement,SVGFEDiffuseLightingElement,SVGFEConvolveMatrixElement,SVGFECompositeElement,SVGFEComponentTransferElement,SVGFEColorMatrixElement,SVGFEBlendElement,SVGEllipseElement,SVGElementInstanceList,SVGElementInstance,SVGElement,SVGDiscardElement,SVGDescElement,SVGDefsElement,SVGCursorElement,SVGComponentTransferFunctionElement,SVGClipPathElement,SVGCircleElement,SVGAnimationElement,SVGAnimatedTransformList,SVGAnimatedString,SVGAnimatedRect,SVGAnimatedPreserveAspectRatio,SVGAnimatedNumberList,SVGAnimatedNumber,SVGAnimatedLengthList,SVGAnimatedLength,SVGAnimatedInteger,SVGAnimatedEnumeration,SVGAnimatedBoolean,SVGAnimatedAngle,SVGAnimateTransformElement,SVGAnimateMotionElement,SVGAnimateElement,SVGAngle,SVGAElement,Rect,Range,RTCSessionDescription,RTCIceCandidate,RGBColor,ProgressEvent,ProcessingInstruction,PopStateEvent,Plugin,PluginArray,PerformanceTiming,PerformanceResourceTiming,PerformanceNavigation,PerformanceMeasure,PerformanceMark,PerformanceEntry,Performance,PageTransitionEvent,OverflowEvent,Notation,NodeList,NodeIterator,NodeFilter,Node,Navigator,NamedNodeMap,MutationRecord,MutationObserver,MutationEvent,MouseEvent,MimeType,MimeTypeArray,MessagePort,MessageEvent,MessageChannel,MediaStreamTrack,MediaStreamEvent,MediaList,Location,KeyboardEvent,InputMethodContext,ImageData,ImageBitmap,IDBVersionChangeEvent,IDBTransaction,IDBRequest,IDBOpenDBRequest,IDBObjectStore,IDBKeyRange,IDBIndex,IDBFactory,IDBDatabase,IDBCursorWithValue,IDBCursor,History,HashChangeEvent,HTMLUnknownElement,HTMLUListElement,HTMLTitleElement,HTMLTextAreaElement,HTMLTemplateElement,HTMLTableSectionElement,HTMLTableRowElement,HTMLTableElement,HTMLTableColElement,HTMLTableCellElement,HTMLTableCaptionElement,HTMLStyleElement,HTMLSpanElement,HTMLShadowElement,HTMLSelectElement,HTMLScriptElement,HTMLQuoteElement,HTMLProgressElement,HTMLPreElement,HTMLParamElement,HTMLParagraphElement,HTMLOutputElement,HTMLOptionsCollection,Option,HTMLOptionElement,HTMLOptGroupElement,HTMLObjectElement,HTMLOListElement,HTMLModElement,HTMLMeterElement,HTMLMetaElement,HTMLMenuElement,HTMLMarqueeElement,HTMLMapElement,HTMLLinkElement,HTMLLegendElement,HTMLLabelElement,HTMLLIElement,HTMLKeygenElement,HTMLInputElement,Image,HTMLImageElement,HTMLIFrameElement,HTMLHtmlElement,HTMLHeadingElement,HTMLHeadElement,HTMLHRElement,HTMLFrameSetElement,HTMLFrameElement,HTMLFormElement,HTMLFormControlsCollection,HTMLFontElement,HTMLFieldSetElement,HTMLEmbedElement,HTMLElement,HTMLDocument,HTMLDivElement,HTMLDirectoryElement,HTMLDataListElement,HTMLDListElement,HTMLContentElement,HTMLCollection,HTMLCanvasElement,HTMLButtonElement,HTMLBodyElement,HTMLBaseElement,HTMLBRElement,HTMLAreaElement,HTMLAppletElement,HTMLAnchorElement,HTMLAllCollection,GamepadEvent,Gamepad,FormData,FocusEvent,FileReader,FileList,FileError,File,EventTarget,EventSource,Event,ErrorEvent,Element,DocumentType,DocumentFragment,Document,DeviceOrientationEvent,DataTransferItemList,DataTransfer,DOMTokenList,DOMStringMap,DOMStringList,DOMSettableTokenList,DOMParser,DOMImplementation,DOMException,CustomEvent,Counter,CompositionEvent,Comment,CloseEvent,ClientRectList,ClientRect,CharacterData,CanvasRenderingContext2D,CanvasPattern,CanvasGradient,CSSViewportRule,CSSValueList,CSSValue,CSSUnknownRule,CSSStyleSheet,CSSStyleRule,CSSStyleDeclaration,CSSRuleList,CSSRule,CSSPrimitiveValue,CSSPageRule,CSSMediaRule,CSSKeyframesRule,CSSKeyframeRule,CSSImportRule,CSSFontFaceRule,CSSCharsetRule,CDATASection,Blob,BeforeUnloadEvent,BarProp,AutocompleteErrorEvent,Attr,ApplicationCache,WaveShaperNode,ScriptProcessorNode,PeriodicWave,OscillatorNode,OfflineAudioCompletionEvent,MediaStreamAudioSourceNode,MediaStreamAudioDestinationNode,MediaElementAudioSourceNode,GainNode,DynamicsCompressorNode,DelayNode,ConvolverNode,ChannelSplitterNode,ChannelMergerNode,BiquadFilterNode,AudioProcessingEvent,AudioParam,AudioNode,AudioListener,AudioDestinationNode,AudioBufferSourceNode,AudioBuffer,AnalyserNode,SVGVKernElement,SVGMissingGlyphElement,SVGHKernElement,SVGGlyphRefElement,SVGGlyphElement,SVGFontFaceUriElement,SVGFontFaceSrcElement,SVGFontFaceNameElement,SVGFontFaceFormatElement,SVGFontFaceElement,SVGFontElement,SVGAltGlyphItemElement,SVGAltGlyphElement,SVGAltGlyphDefElement,SpeechInputEvent,WebKitShadowRoot,ShadowRoot,webkitAudioPannerNode,webkitIDBTransaction,webkitIDBRequest,webkitIDBObjectStore,webkitIDBKeyRange,webkitIDBIndex,webkitIDBFactory,webkitIDBDatabase,webkitIDBCursor,WebKitMutationObserver,webkitURL,WebKitTransitionEvent,CSS,performance,console,devicePixelRatio,styleMedia,parent,opener,frames,self,defaultstatus,defaultStatus,status,name,length,closed,pageYOffset,pageXOffset,scrollY,scrollX,screenTop,screenLeft,screenY,screenX,innerWidth,innerHeight,outerWidth,outerHeight,offscreenBuffering,frameElement,event,clientInformation,navigator,toolbar,statusbar,scrollbars,personalbar,menubar,locationbar,history,screen'.split(',');
  var g_ = Object.getOwnPropertyNames(self);
  return g_.filter(function(x) {return !~GLOBALS_.indexOf(x);});
})(this);

他のブラウザやバージョン違いでの作り方

まずは、そのブラウザをブランクページで開きます。
chromeであれば、urlにabout:blankと打ち込みます
その後、コンソールを開いてください。そこに次のように打ち込んで結果を上記のGLOBALS_に代入するとそのブラウザ用のものが出来ます。

Object.getOwnPropertyNames(this);

(上記では、一度カンマでjoinしたものを代入し、splitしていますが、そのままでもかまいません)

他のウェブサービスを参考する

例えばQiitaの記事ページで実行すると次のように出力されます

["_", "___jsl", "optimizely", "mixpanel", "loadrunner", "Qiita", "_gaq", "gaGlobal", "__twitterIntentHandler", "store", "_gat", "jQuery1110007918387488462031", "bundle", "optly", "google_tag_manager", "$", "osapi", "provide", "Backbone", "gadgets", "define", "Iframe", "GoogleAnalyticsObject", "__twttrlr", "iframes", "I18n", "IframeProxy", "__gapi_jstiming__", "twttr", "IframeBase", "FB", "jQuery", "shindig", "Hatena", "optimizelyCode", "ga", "key", "ToolbarApi", "dataLayer", "iframer", "using", "IframeWindow", "gapi", "gaplugins", "JST"]

随分といろいろなライブラリを利用している見たいですね。
参考にしたいウェブサービスがどのようなライブラリが読み込まれているのかを、参考程度ですがさくっと見る事が出来るかもしれません(保証無し)

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?