JavaScript Web Development

Understanding JavaScript’s this keyword

I presented a talk about JavaScript’s this keyword at the JSChannel Conference Delhi this Saturday.

The this keyword in JavaScript can get quite tricky, especially in event callbacks and setTimeout() or setInterval() handlers. In this presentation, I discussed common usage patterns that lead to an unexpected value of this, as well as provided recipes to code these patterns the right way.

The presentation can be viewed at http://toshsharma.github.io/presentation-this/.


Outline

  • this in Object methods, getters & setters
  • this in Function calls
  • this in Extracted object methods
  • this in setTimeout, setInterval callbacks
  • this in event handlers
    • <span onclick=”hander()”>
    • <span onclick=”hander(this)”>
    • <span onclick=”handler”>
    • element.onclick = handler;
    • element.addEventListener(“click”, handler);
  • this in jQuery event callbacks
  • this in constructors
  • this in eval’ed code
  • this in Nested functions
  • this and Array.prototype.{forEach,map, filter, every, some}, jQuery.each
  • Inheritance and this
  • Inspecting this in the current scope
  • Creating a closure – self, thiz, that
  • Explicitly setting the value of this
    • call, apply
    • bind
Share this:
Twitter Email
JavaScript Tutorials Web Development

Executing JavaScript Code on a Web Page as a Chrome Extension

I often create bookmarklets to help me with specific tasks in my web development (e.g. removing all CSS from a document). These contain some JavaScript code that I want to execute on arbitrary web pages. When I want to share these little tools with someone, I often create Chrome extensions (.crx files) which others can download and easily install.

In this post, I’ll talk about how you can create a Google Chrome extension for code that operates on opened web pages and runs in their context. The extension (.crx file) can then be shared with someone, or be uploaded to the Chrome Web Store.

This tutorial is for JavaScript code that runs directly on a web page (as if it was included in the web page) and does not invoke any Chrome extension APIs. For example, you could write JavaScript that overrides a site’s CSS styles, or hides replies on a user’s Twitter page.

In addition to creating Chrome extensions from scratch, you can also use this as a template to create Chrome extensions based on existing bookmarklets.

To create the Chrome extension:

  1. Download the following template file:

    extension.zip

  2. Unzip the file. This creates a folder named extension.
  3. Look for a file named contentscript.js, and add your code to it (without the “javascript:” prefix, in case of an existing bookmarklet’s code).
  4. Modify the name, description, version, icon and permissions for your extension in the file manifest.json. You can find more details in Google’s developer docs for extension manifests.
  5. Navigate to chrome://extensions/ in Google Chrome.
  6. Enable “Developer Mode”.
  7. Click “Pack extension” (or “Load unpacked extension” if you want to try the extension first).
  8. Developer nide

  9. Select the “extension” folder as the “Extension root directory”. You may leave the “Private key file” field blank (Chrome will generate a key for you).
  10. Pack extension

  11. Click “Pack extension”. Chrome will let you know the location of the created extension file (.crx).

You can send the generated extension (.crx file) to anyone. To install the extension, the recipient will need to open chrome://extensions in a new tab in Google Chrome, and drag and drop the .crx file onto that page. The extension’s functionality can be invoked via the icon that gets added next to the address bar in the browser.

If your JavaScript code has a dependency (e.g. jQuery), you can add .js files to the unzipped folder (e.g. jquery-1.9.1.min.js) and have them included in background.js before contentscript.js:

contentscript.js can then use jQuery (or $):

Any console.log statements in contentscript.js will print to the webpage’s console (Cmd-Alt-I (Mac) or F12 (Win)). However, to debug background.js (or see the output of any console.log statements in it), you’ll need to open up chrome://extensions/ and “inspect” background.html for your extension – this will open up a new Chrome DevTools window that shows the output from background.js.

Inspect background.html

For more details on creating extensions, you can head over to Google’s developer docs.

Share this:
Twitter Email
CSS Tools

Hacking Chrome DevTools – Look and Feel

Google Chrome allows you to specify CSS styles that can override the built-in styles (user agent styles). This is typically used to override styles of web pages. However, it can also be used to target the built-in developer tools (DevTools), changing how it looks.

Some reasons why you might want to modify the look and feel of DevTools are:

  1. Hiding user agent styles in the “Styles” sidepane. (BTW, a DevTools setting exists for this.)
  2. Achieving a similar look and feel as that of your favorite editor, for the Sources panel
  3. Improving the readability of DevTools

Many of the existing CSS rules used to style DevTools can be seen at:

chrome://devtools/devTools.css

However, there are many more CSS stylesheets that contribute to the look and feel of the individual panels in DevTools (e.g. elementsPanel.css). You can look at these to find rules to override:

auditsPanel.css, breadcrumbList.css, breakpointsList.css, canvasProfiler.css, cmdevtools.css, codemirror.css, cssNamedFlows.css, dataGrid.css, elementsPanel.css, filteredItemSelectionDialog.css, flameChart.css, heapProfiler.css, helpScreen.css, indexedDBViews.css, inspector.css, inspectorCommon.css, nativeMemoryProfiler.css, navigatorView.css, networkLogView.css, networkPanel.css, panelEnablerView.css, profilesPanel.css, resourcesPanel.css, resourceView.css, revisionHistory.css, scriptsPanel.css, sidebarPane.css, spectrum.css, splitView.css, tabbedPane.css, textEditor.css, textPrompt.css, timelinePanel.css

Since Chrome won’t load the above links if you click on them (they are local resources), please right-click on a link, select “Copy Link Address” and then paste it in a new tab.

(This is the list of all .css files under src/out/Release/obj/gen/devtools/ in Chrome’s source code. Some of the .css files at src/third_party/WebKit/Source/devtools/front_end/ are already concatenated into src/out/Release/obj/gen/devtools/devTools.css.)

Once you’ve decided which rules to override (or new ones to include), you can add them to a file Custom.css. This file is located at the following location:

Mac
/Users/Username/Library/Application Support/Google/Chrome/Default/User StyleSheets/

Windows
%LOCALAPPDATA%\Google\Chrome\User Data\Default\User StyleSheets\

Linux
~/.config/google-chrome/Default/User StyleSheets/

To restrict your style changes to DevTools (and not inadvertently affect web pages themselves), you should scope all of you CSS rules by prefixing each selector with #-webkit-web-inspector, which is the ID of the DevTools’ body element.

Chrome automatically reloads any changes you make to Custom.css – you do not need to relaunch the browser (or even DevTools) for your changes to take effect – you might need to wait a couple of seconds though, for your changes to be picked up and applied by the browser.

If you want to debug your styles (or simply understand more about the DevTools), you can actually debug DevTools using DevTools itself:

  1. Open DevTools (Cmd-Alt-I (Win) or F12 (Win))
  2. Undock DevTools into a separate Window – click on the dock-selector button near the bottom-left corner of DevTools. You might need to long-click on the button for the “Undock into separate window” option to show up.
    Undock DevTools
  3. Press Cmd-Alt-I (Mac) or F12 (Win) to open a new DevTools window to debug this DevTools window.

The newly opened DevTools window can then be used to inspect the styles (and more) of the original DevTools window.

Any CSS rules added to Custom.css will show up under “user agent stylesheet” in DevTools (Styles sidepane in the Elements panel).

Let’s look at an example. If you want to remove specific panels from DevTools, you can look up the appropriate selector (from the .css files or via DevTools) and hide them as follows:

Note that you might have to use !important with your properties, depending on how specific your selector is.

People have created several skins or themes for Chrome DevTools, by modifying Custom.css. You can find many of them at http://devthemez.com/themes/chrome-developer-tools.

Share this:
Twitter Email