Generic Ajax Widget

As part of this article, I've included a generic Ajax widget that simply grabs a URL and parses out a small section of the DOM that I'm interested in.
It’s a good jumping off point to get going with an Ajaxified widget.




Getting Dashcode

If you've got a recent version of Leopard or Tiger, the system Disks will contain Dashcode in the developer kit (it may be installed already in your /Developer/Applications directory).
Apple did have Dashcode available for download, but since it expired in July (when Leopard was to come out) it’s no longer there.
You can hunt around the Internet for a old mirror if you don't have the CDs.
Once installed, it'll say it’s expired: just get Dashcode working again.

Stability

Broken Dashcode RenderDashcode is particularly ropy with Safari 3.
With Safari 2 it’s much more stable. Since there is the occasional crash from Dashcode,
I would recommend constantly saving your project as you're coding.
I found more than 10% of the time, Dashcode would crash and result in a total loss of my code from the last save point.

Also, I've noticed that dumping a lot to the run log, when viewing the log, can cause Dashcode to slow right down to almost hanging.
Best to avoid dumping large amounts of HTML to the log.
However - and this is a big one - the upside of programming with Dashcode is worth the risk of the crash, because it’s takes most work out of the design process.
Since you're using it’s GUI to drag and drop your design and how the user will interact with it, rather than having to code the look and feel by hand.



Designing Widgets

The interface and the library component of Dashcode makes it possibly the strongest app for developing widgets. It’s 2 minutes work to create a glass effect on your widget, or to place the elements on the window and get going.
I would strongly recommend studying other widgets, and reading through the Dashcode design recommendations as it’s easy to design a widget that works, but twice the work to design a widget that’s usable and works well.
You'll find you can place widget-type objects on your widget, like scroll areas or gauges - but to handle them in the code isn't entirely intuitive, which is why the best source of understand how these interface elements work, is by opening up other widgets that already make use of the element.




Controls

Dashcode offers the easy integration of bespoke elements such as the scrollarea, gauges and other such sexy components.
They're pretty easy to drop on to the widget from Dashcode, but until you're coding, they're not immediately obvious how they work.
The help is limited, so I would recommend to develop by tutorial, in particular, look for the 'refresh()' methods - as this seems to be a fairly standard way to redraw objects.
Full documentation for the Apple classes API is available, but it’s pretty clinical.




Effects

Although effects are available within the Apple classes, you'll need to implement them yourself.
This is fairly limited to dynamic resizing of the widget, which is achieved using:

window.resizeTo(x, y);

If you are going to resize the widget dynamically, check out the Apple resizing examples too.
I used this technique in my HTML entities widget to keep the widget small when it’s dropped in to the Dashboard, but to allow it to grow dynamically when the user searched for a particular HTML entity.
You should be able to find easing effects code and examples if the built in Apple animation class doesn't suite your needs.



Running system commands


This is one of the few areas that’s well documented in the provided API.
You can run system commands using the following type of command:

widget.system('ps -auxww | grep ' + myCommand, null);
What you should keep in mind, is that you can run any command through the system method. This includes Perl, Ruby, AppleScript and anything else that suits your needs.
Using these commands I've recently been able to create a widget that queries Mail’s SQLite’s database via Perl.
It was a case of running the system method and capturing the output (and in my case, eval'ing it from a JSON output).




Ajax in the widget


You widget supports a variation of the Ajax object (or rather xmlhttprequest object).
This version isn't bound by the usual security constraints of a browser - most importantly, it can request content from any domain.

To execute any Ajax requests from your widget, ensure you have the Allow Network Access attribute turned on - otherwise the Ajax will fail without any given reason.

For example, you could use Ajax to pull your film page from IMDb and then parse the XML for the elements of interest.

However, if you do want to pull some data from a web page and process it using the DOM returned you have to fiddle the request - in particular the responseXML will be null because the page being returned isn't text/xml - it’s text/html. You can do it using the following (in jQuery syntax):

$.ajax({
url: 'http://remysharp.com/example_page', // doesn't really exist!
dataType: 'html', // important
success: function (xml) {
// convert the HTML to an XML DOM object
var dom = getDOMfromXML(xml);
alert(dom.getElementsByTagName('h1').length);
}
});

function getDOMfromXML(xml) {
var d = document.createElement('div');
xml = xml.substring(xml.indexOf('<body') + xml.substring(xml.indexOf('<body')).indexOf('>')+1);
xml = xml.substring(0, xml.indexOf('</body>'));
d.innerHTML = xml;
return d;
}

This getDOM function is pretty horrible - but it works. I tried using DOMParser and tried using Ajax local data trick and I tried using an iframe to inject the XLM - but neither would load the XML properly (in fact it would be blank).
The iframe would not load properly because it was still loading the entire frame while I was trying to access it.

You can see this in use in the generic Ajax widget or download the source Dashcode project.



Widget Attributes


The widget attributes are fairly self explanatory, but it’s worth knowing:
  • Allow Network Access is required for Ajax requests
  • Allow Command Line Access is required for running external programs, i.e. if you have a Perl script executing some arbitrary task

If you intend to make your widget available in different languages, then this is the place to enter the different strings.

The Inspector

  • Hide items from the default image to present a better widget when it’s installing. It can to keep the preview of your app looking clean.

Debugging


Dashcode comes with a log that can be viewed during run time.

You have following debugging tools:
  • Breakpoints
  • Live stack traces
  • Evaluate window - to test commands

To write to the log, you need to use alert("My debug message");.
Tip of the Day News Mac Tips and Tricks Games ★★★★★ Tips+Tricks MacTips WebApps Tips + Tricks Widgets Downloads iPhoto Safari Tips Apple Free Apps Personal GarageBand iMovie Internet Utilities Multimedia Apple Downloads Pro Tip iWeb Dashboard iTunes Mac Dashcode iDVD DashboardClocks Support 10.8 Applications iLife News OSX Tutorials 10.7 Desktop Mac Tip of the Day AppleTV Dashboard Widgets Finder Firefox MacWidgets OS X Mountain Lion Tips and Tricks TopApps Videos 10.6 Keyboard Shortcuts iPad iPhone Mac 10.9 AirPlay Apps on Mac Dock Just Added Mac App Store MacApps MacNN OS X OS X Lion Softpedia Tricks Updates iCal iLife iLife Widgets iPhone Tips and Tricks FAQ Mail AppShopper.com AppleNews Application Tips Customizing Customizing Your Mac Dashboard Guidelines Developer Widgets Exposé Games Widgets Mac App Store - News Mac OS X 10.6 Mac OS X 10.8 Mountain Lion Mac101 MacNews MacUpdate Mac|Life OS X Daily Preview Snow Leopard Tips Terminal TextEdit Top10 Mac Tips VersionTracker Video Tutorials Windows iCloud iLife 11 iWork  Navigation Key Combos Mac 101 MacSupport OS X 10.8 Mountain Lion OS X Mavericks Search Widgets Security iDVD Widgets iPod 10 Keyboard Shortcuts for Text 9 to 5 Mac A A-Z Glossery - iPhone App ATMac Address Book App App Store - News AppShopper Apple Gazette Apple Keynotes Apple Matters Apple Pro Apple Support Tips Apple Updates AppleInsider Applelinks Apps A-Z Apps Apps Apps Apps on Mac - Dashboard Widget Asteroid Audio Automator B BindApple Blogs + Forums Widgets Business Widgets C Calculate + Convert Changing the background Check external devices Check spelling and grammar Clear Versions History + Auto-Save Cache Data Cult of Mac Cydia D Daily Tips and Tricks Dashboard - Tips+Tricks Dashboard Tips and Tricks Dashboard Widget DashboardCandy DashboardSearch DashboardWidgets.com Desktop Computers Developer Forum Developer News Developer Tips Development Tools Disable restored windows when re-opening specific apps Discussions Display a login banner Display a short message Display system stats Dual Boot OS X 10.7 Lion + OS X 10.8 Mountain Lion E Easy Mac Tips Email + Messaging Widgets Essential Expose Extract and Save Mac Application Icons F Find a MAC Address in Mac OS X Find iMessage Users + Contacts Folders Food Widgets Freeware G Get iTunes track notifications in your Dock Get quick information with widgets Google News H Hackint0sh Hacks Hongkiat How To How to disable the Java web plug-in I IT Industry Today Icons Icons + Screensavers Image Capture Information Widgets InsanelyMac Installation International Widgets J Just Added - iPhone Apps Just Added Downloads Just For Fun Widgets K Keynote Address L Launchpad for Mac OS X Snow Leopard Links Lion M Mac App Store - Business Mac App Store - Developer Tools Mac App Store - Education Mac App Store - Entertainment Mac App Store - Finance Mac App Store - Games Mac App Store - Graphics + Design Mac App Store - Health + Fitness Mac App Store - Lifestyle Mac App Store - Medical Mac App Store - Music Mac App Store - Photography Mac App Store - Productivity Mac App Store - Reference Mac App Store - Social Networking Mac App Store - Sports Mac App Store - Top 50 Mac Apps Mac App Store - Travel Mac App Store - Utilities Mac App Store - Video Mac App Store - Weather Mac Developer Tips Mac OS X Mac OS X 10.7 Lion Mac OS X Applications Mac OS X Things Mac OS X Tips Mac OS X Tips - News Mac OSX Hints Mac OSX Hints - News Mac Quick Tips Mac Tips Mac Tips Daily Mac Tips and Tricks - Desktop App Mac Tips and Tricks - Mac OS X Dashboard Widget Mac360 MacApp MacApper MacFixIt MacLion MacMusic MacOSXAudio.com MacRumors MacTech MacUpdate.com MacintoshOS.com Maciverse Macworld.com - iPhone App Reviews ManiacDev MobileMe News ModMyi.com Most Recent Movies + TV Widgets Music Widgets N Navigating + Selecting Text in Mac OS X Networking + Security Widgets New Application Tips New iPhone Apps News Widgets News on Mac Notification Center O OS X - FAQ OS X 10.7 OS X Basics OS X Mac Tips + Tricks OS X Mountain Lion - News OS X Snow Leopard OSX Basics Open source OpenDashboard P Pages Podcast Widgets Portable Computers Ports and Connectors Preferences Press Release Q R Radio + Podcasts Widgets Rampant Mac - iPhone Wallpapers Rename Files and Folders Restart an external device S SD and SDXC card slot FAQ Safari 5.1 Safari 6 Safari Videos Scheduled Startup and Shutdown Set Up Storage Devices Set up iCloud Shopping Widgets Simple Desks Snow Leopard Softonic - Mac Softonic.com Softpedia - Tips + Tricks Softpedia.com Stacks Staff picks Status Widgets Storage StorePreview Switch 101 Syncing with iTunes System Preferences T TUAW The Apple Blog The Apple Core The Mac Observer The Mac Screencast Guy The MacTips Podcast TheDashboard Time Machine Tools Top 10 Grossing Apps Top 25 Grossing Apps Top 50 Grossing Apps Top iTunes Tips Top10 Paid Apps Top10 Widgets Top50 Dashboard Widgets Translates Transportation Travel Widgets U Updating Useful iPhone Shortcuts Using iChat V W Wallpaper Want More Mac Tips ? Web Apps Webcam Widgets Widget Work X YouTube Videos Z ZDNet apple.stackexchange.com digg gSearch - iPhone App iChat iClarified iCloud + MobileMe iCloud News iCloud system requirements iDesign - iPhone Wallpaper iHackintosh iLife - iPhoto - iMovie - iWeb - GarageBand - iDVD iLife Discussions iLife Discussions - GarageBand iLife Discussions - iDVD iLife Discussions - iMovie iLife Discussions - iPhoto iLife Discussions - iTunes iLife Discussions - iWeb iLife Support iLife System Requirements iLife ’09 iMovie Widgets iOS 4 iOS Developer News iPad - News iPhone - News iPhone 4 iPhone App iPhone SDK iPhoto Widgets iPod - News iPod News iPod Tips and Tricks - iPhone App iPod touch iTunes - Latest Movie Trailers iTunes - News iTunes - Top News iTunes App Store iTunes App Store - All New Applications iTunes Keyboard Shortcuts iTunes News iTunes Plus FAQ macosxtips.co.uk switchtoamac.com thinkmac.net www.freemacware.com ...organise your mac 10 Quick Mac Tips 10.10 101 ASC Animation Slow-Mo Aperture Aperture Glossary Apple Support Communities Boot Camp Bored of your Mac? Collect RSS feed URLS from Mail Create Ringtones in iTunes Customise your desktop + screen saver Does your Mac qualify for free 10.8 upgrade? Download Download YouTube and Other Videos FTP FTP with Finder Finder Tips Gatekeeper Get Mac News Get More Mac and iOS Tips Get More Mac and iOS Tips... Get OS X Tips Get RSS Menu Extension for Safari 6 Get Windows Live Hotmail with Mail Get Yahoo Mail with Mail Get a Homepage - Mac OS X Style Glossary Google Hidden Features Hidden Features in OS X 10.8 Mountain Lion Hotmail Install Windows 8 on a Mac Mac 101 - Get One on One with your Mac... Mac OS X Dashboard Widget Mac Support Mac Tips and Tricks - Learn how to set up MacBasics MacHelp MacVideos News and Help Notification Center Tips OCD Friendly Volume Controls OS X 10.5 to 10.8 Upgrade OS X Features OS X Mavericks Tips OS X Mountain Lion Hompage OS X Mountain Lion Installation Guides OS X Tips Organize Your Dock Quick Define Quick Googling Quick Math RSS Remote Folder and Synchronization Remove Dock Icons in OS X Mountain Lion Reset specific parts of Safari ScreenCast Online Screenshots Search Search Google Search Mac Tips and Tricks Second Clipboard Security Tips Siri Siri Tips Snippets Speed Up Your Mac Stop Automatically Updates Summarize Text System Configuration Take advantage of Quick Look Taking Screenshots Text Tip Tips and Support Top Mac Tips Top Security Tips USB 3 devices on Mac - FAQ Use Smart Folders effectively Which Mac is Worth Your Investment? Widgets On Your Desktop Windows 8 Xcode Xcode Tips Yahoo YouTube iOS Support iPad Support iPhone Support iPod Support onemac.net onemac.org use and troubleshoot your Mac