Pageflakes API Reference

This section describes the various interfaces of the Pageflakes framework.

Flake System Object

The Flake System Object enables the code within the Flake User Object to interact with the Pageflakes framework, and access certain functions and variables that pertain to the flake instance in question.

The Flake System Object is accessed through the "instance" variable that is passed to the load() function of the Flake User Object. As a convention, the Flake User Object stores the reference to this instance in a variable called _instance.

toggleEdit() Toggles between the normal flake mode and edit mode.
showEditArea() Switches the flake to edit mode.
hideEditArea() Switches the flake to normal mode.
resize() Forces a resize of the currently displayed page.
close(force) Closes the flake instance. If force is set to true, no confirmation dialog box is shown.
canClose() Returns true if the flake can close, false otherwise. This behavior can be implemented by defining the beforeClose() function (see below).
setTitle(title) Changes the title on the flake title bar. This is not saved to permanent store, unless the save() function is called.
save() Saves changes made on the Profiles or title.
collapse() Collapses the flake.
expand() Expands the flake.
setIcon(url) Sets the icon to the provided URL. URL must point to a 16x16 pixel .gif or .jpg image.
editEdit() Saves the flake's title under the "Preference" tab in the flake's setting section.
enableRefresh() Enables the flake's refresh button.

See also: refresh() of the Flake User Object

disableRefresh() Disable the flake's refresh button.

See also: refresh() of the Flake User Object

dispose Disposes the instance of the flake.
setNumber() Displays a number in parentheses at the end of the flake title. This can be used for any number of applications, such as number of unread emails, or number of unread RSS items.
clearNumber() Removes any number on the flake title that was set using setNumber.
beforeClose() This function is called when a flake instance is about to be closed. If this function returns false, the flake is not closed. If desired, this function is defined by the flake developer. For example:


 this.load = function(instance)
 {
   _instance.beforeClose = function()
   {
    // do some checking
    return false; // prevent from closing
  }
}

Storing Data with Profiles

The Flake System Object provides profiles with objects for storing data. Profiles can be treated similar to a hash table, and can store any data identified by a key. The following code shows an example of this.

fso.Profiles['key']=value;

This code demonstrates the general way of staring data into instance profiles. If a value is set against a key, permanent storing requires calling a save() method of the instance as shown below.

fso.save();

Once this has been called, the data can be safely retrieved for later use from this array by the following key.

var mydata = fso.Profiles['key'];

Note:

  • Storing large data chunks in a profile slows down the flake's performance. The maximum size allowed is 8KB per item. For example, if your flake retrieves data using the ContentProxy, instead of directly storing all the results, it is better to parse the results and store only a smaller subset. In fact, unless you have a good reason to cache the data (e.g. it may be unavailable in the future), it is best to just retrieve the data through the ContentProxy whenever you need it.
  • Calling fso.save() in the load() function of the Flake User Object slows down the page load time significantly.
  • Only string values can be stored. To store an array, join the array into a delimited string, as described in Storing an Array into a Profile.
  • Confidential information such as usernames and passwords should not be stored in a Profile in plain text.

Flake User Object

The Flake User Object is defined by the flake developer.

load(fso)

This function must be defined. It is called by the framework when the flake is loaded. The load() function takes a single parameter instance which holds a reference to the Flake System Object. The instance parameter should be stored for future use.

onclose()

This optional function (if defined by the flake developer) is called when the user accepts the confirmation and the flake is ready to be closed. This function can be used to perform cleanup operations related to the flake instance.


      function com_pageflakes_devdocs_exampleflake()
      {
        this.load =
        function(instance) { ... }
        this.onclose =
        function() { ... cleanup stuff ... }
      }
      

dispose()

This function is created by the flake developer to dispose any data or references the flake is holding on to. Failing to dispose of resources used by your flake can cause memory leaks in Internet Explorer 6.
Such leaks make the browser slow, consume memory and can crash the browser.

The following actions must be performed in the dispose() function:

      Release references to UI elements (for example, references to <div> elements).
      Detach all event handlers from UI elements.
      Clear all arrays or large string variables which consume memory.
      Remove IFRAME elements, which can leak memory.

For example:


      dispose : function()
      {
        this.someDiv = null;
        PF.detachEvent(this.someDiv, 'click', this.clickHandler);
        this.someBigArray = null;
        PF.remove(‘myIFRAME’);
      }
      

refresh()

This function can created by the flake developer and is called by the framework when the user clicks on the Refresh button.

See also: enableRefresh() and disableRefresh() of the Flake System Object

Pageflakes Functions

The Pageflakes framework provides a set of functions that have been designed to work across all the major browsers, such that concise, platform independent code can be used to build flakes.

All the functions shown below are members of the PF object. They can be accessed by calling PF.functionName().

DOM Manipulation

$(id)

Shortcut for document.getElementById:


var e = document.getElementById('mytextbox');

Use:

    var e = PF.$('mytextbox');
    var i = PF.$('myradiobutton');
    

$$(tagName, id, className, text)

Shortcut for document.createElement.

The tagName parameter must be specified. All other parameters are optional.


var div = PF.$$('div');
var divButton = PF.$$('div', 'button', 'button_class', 'this is a button');
      

remove(e, p)
remove(id)
Removes the element from the parent node.
removeAll(el) Removes all child elements from the element. It recursively traverses all children and calls remove on them.

Example

This example demonstrates how to perform some simple DOM manipulations, including assigning an element to a variable and removing an element using the PF.Remove method.

Element Visibility

nodisplay(e)
nodisplay(id)
ND(e)
ND(id)

Instead of:

e.style.display = "none";

Use any of the following:

PF.nodisplay(e);
PF.nodisplay('mydiv');
PF.ND(‘mydiv’);

T(e, text)
T(id, text)
setInnerText(e, text)

Instead of:

if (mz)
	  e.textContent = text;
else
	  e.innerText = text;

Use either of the following:

PF.T('mydiv', 'text to set');
PF.T(e, 'text to set');

display(id)
D(e)
D(id)

Instead of:


e.style.display = "block";

Use any of the following:

PF.display(e);
PF.display('mydiv');
PF.D(‘mydiv’);

isVisible(e)
isVisible(id)

Returns true if the element
is visible; false otherwise.
clearDisplay(el) Clears the e.style.display property and reverts to what is defined in CSS.
hide(el) Sets visibility style to hidden.
visible(el) Sets visibility style to visible.
toggleDisplay(el) Toggles display attribute to show/hide element.
switch(display, nodisplay)

Displays the first item and hides the second item.


PF.switch( divToShow, divToHide )

toggleVisibility(name) Toggle display style between “none” and “block”.
canYouSeeMe(target) Returns true if the item is
visible on the screen, or false if it is not
visible. It does so by walking through the ancestors and checking whether any
of them has the display attribute set to none or the visibility attribute set to hidden.

Element State

focus(e)

focus(id)

Sets focus to the element.

disabled(e)

disabled(id)

Disables an element. No mouse events will be captured.
Text color is changed to lightgrey. Useful
for disabling buttons. For example:


PF.disabled('mybutton');

Or:


PF.disabled(e);

enabled(e)

enabled(id)

Enables the element that had been disabled. For example:

PF.enabled('mybutton');
PF.enabled(e);
      

disableAllFrames()

Disables all frames and IFRAMEs on the page by setting
their enabled property to false.

Class Manipulations

addHover(el, className)

Adds hover behavior to an element. When the mouse hovers over the item, the specified class is added to the element. When the mouse leaves, the specified class is removed.

addClass(el, className)

Adds a CSS class to an element. Previous classes are preserved.

removeClass(el, className)

Removes a particular CSS class from element.

select(item, className, tagName)

When a series of elements exist where only one can be selected at a time (e.g. tabs or radio buttons), this function can be used to apply a class to the selected item and clear that class from unselected items.

<div onclick='PF.select(this, "selectedClass", "div")'>Item 1</div>
<div onclick='PF.select(this, "selectedClass", "div")'>Item 2</div>
<div onclick='PF.select(this, "selectedClass", "div")'>Item 3</div>

selectChild(parent, tagName,
className, expr)

Apply a class to child elements of a node based on some expression. Consider the following example:

    <ul id="tabs">
        <li>Tab 1</li>
        <li>Tab 2</li>
        <li>Tab 3</li>
    </ul>

Now, to modify the class of a particular tab, the following can be used:

PF.selectChild('tabs', 'li', 'selectedTab', function(tab) {
    return tab.innerText == 'Tab 2'; } );

This example assigns the 'selectedTab' class to 'Tab 2'.

In general, the specified class is assigned to the all elements where the specified function evaluates to true.

Positioning

centerDiv(div) Position an absolute div at the center of the visible area.
changeParent(id, newParentId) Move an element from its current parent to the new parent.
makeOnTop(el) Position the absolute element on top of any other absolute element.
getPosition(obj) Get the bounds of the specified element as an array. For example:


var pos = PF.getPosition(e);
x = pos[0];
y = pos[1];
w = pos[2];
h = pos[3];

Cursor

setBusy() Change the cursor to hourglass.
setIdle() Set cursor to the default arrow.

Progress Bar

showProgress() Display the progress bar.
hideProgress() Hide the progress bar.

Element Opacity

setOpacity(id,val) Set the opacity of an element.
changeOpacity(opacity, id) Changes the opacity of any given element by 'opacity'.
clearOpacity(id) Makes an element 100% opaque.
opacity(el, startOpacity, endOpacity, millisecond, callback) Change the opacity from a given value to new value within a fixed time defined in milliseconds. When execution is complete, the callback is invoked.
shiftOpacity(id, milliseconds) Toggles the opacity from 0 to 100 of a given element in the specified time period.
currentOpacity (id,opacEnd,millisec) Change the opacity from the current value to the specified ending value within the given time (specified in milliseconds).

Cookies

createCookie(name, value, day) Creates a cookie with the given name, value, and expiration (in days).
readCookie(name) Returns the value of the cookie
cloneObject(ob) Makes a clone of an object by copying all of its properties and  functions.

var clone = new PF.cloneObject(someObj);

Miscellaneous

addScript(id, url)

Adds a script tag in the <head> section. Use this to dynamically download script blocks.

htmlEncode(text)

HTML encodes a string by replacing special characters with
their HTML equivalents.

urlParam(name)

Returns the value of the query string parameter.

For example, if the current URL is:

http://example.com/default.aspx?id=123

Then to get the “123” value the following can be used:

var id = PF.urlParam("id");

dumpException(exp)

Used to handle exceptions produced form server side calls.
Whenever you call a server side method, the 3rd argument is an exception
callback. For example:

this.callback = function(result) { ... }
this.error = function(exception)
{
  PF.dumpException(exception);
}
ContentProxy.GetUrl(url, callback, error);

isFlashInstalled()

Returns true if a Flash player is installed, false
otherwise.

getErrorMessage(exp)

Get the error message from the exception.

exec(string)

Executes any JavaScript code passed as parameter.

stripTags(value)

Removes all HTML tags from the provided string and returns the result as a string.

formatText(text)

Format the supplied text by replacing line breaks with <br/>.

helpText(textbox, text)

This function grays out the specified text box, filling it in with the text specified. This can be used to provide help text on how the text box should be filled in.

When the user selects the text box, the box clears the text and restores the normal background color.

Events

F(object, function)

Delegate

Returns a delegate reference that fires the function on the context of the passed object. F(...) should be used in callbacks such that the callback can use the this pointer. For more information see Avoid memory leaks and understand 'this'.

ContentProxy.GetUrl(url, PF.F(this, this.callback));

addEvent(e, eventName, handler)

Adds an event handler to an element. This is a cross-browser solution for subscribing events on UI elements. The following way of hooking into events should not be used:

Somebutton.onclick = function(e) { }

This leaks memory in Internet Explorer 6 if not used carefully. Moreover, it removes any existing event handler on the same event. Instead, do it this way:

PF.addEvent(Somebutton, 'click', callback);

And define the callback function outside the scope:

function callback(e) { ... }

The benefit of this type of event handler is that the event parameter is passed in the callback in a cross-browser implementation. This e has the same parameters and functions in all browsers.

removeEvent(e, eventName, handler)

Removes an event handler from an element. However, only event handlers that were subscribed by calling addEvent can be removed.

This function ensures that event handlers are released properly to prevent IE 6 from leaking memory. Event handlers should be removed as soon as they are no longer required.

PF.removeEvent(somebutton, 'click', callback);

removeAllEvents(e)

clearEvent(e) [deprecated]

Clears all event handlers from an element. This ensures that the DOM element is ready to be released and solves a memory leak problem in Internet Explorer 6.

fix(event)

IE treats events differently that other browsers. IE uses window.Event which Firefox doesn't support. Moreover, most browsers pass the event as an argument to the event callback function, which IE does not.

In order to avoid such problems, all event handlers can be declared by giving them an argument for getting the event, and inside the event,  the fix function can be invoked to ensure that the event parameter has the right value. For example:

function onresize(event) { event = PF.fix(event); ...}

It is also possible to use the Callback function, described below.

Callback(code)

This method provides a browser independent method of invoking event callbacks (for additional information see also the fix() function above).

Specifically, it takes care of the difference between Internet Explorer, and all other browsers in passing the event data to the event handler. For example:

PF.addEvent(item, 'click', PF.Callback("alert(event.target)");

The code is evaluated only when the event fires.

The function is defined as:

PF.Callback = function(code)
    {
      return function(event)
      {
         event = PF.fix(event);
         eval(code);
      }
    }

stopBubble(event)

Prevents the event from bubbling up to the parent element.

delayCall(func)

DC(func)

Calls the specified function in a timer with near zero delay. In Firefox, if the innerHTML of an element is set and the child nodes are accessed immediately, the operation will sometimes fail since the DOM elements are not immediately available.

As a workaround, the following code can be used to complete the code execution and access the elements with a delay:

div.innerHTML = "<div id='childDiv'>...</div>";

// This will fail in FF sometimes if the browser does not create
the childDiv immediately

PF.D('childDiv');

// This will not fail

PF.DC( function() { PF.D('childDiv') } );

Window

scrollTop()

Scrolls to top of the page.

scrollBottom()

Scrolls to bottom of the page.

getContentHeight()

Returns the height of the document.

getViewportWidth()

Returns the width of the window.

getViewportHeight()

Returns the height of window.

getViewportScrollX()

Returns the horizontal scrollbar position

getViewportScrollY()

Returns the vertical scrollbar position

XML

getXmlDoc(xmlString)

Returns an XML DOM object from an XML string.
Use the DOM object with the following two functions.

getFirstNode(xmlDoc, pattern)

Returns the first XML node from the provided XML document that matches the provided pattern. For example:

var node = PF.getFirstNode(xmlDoc, "book");

To find an element by specifying multiple node names, use a pattern like this:

var node = PF.getFirstNode(xmlDoc, "book:author:firstname");

getNodes(xmlDoc, pattern)

Returns and array of XML nodes (JavaScript Node objects) from the provided XML document that match the provided pattern. For example:

var nodes = PF.getNodes(xmlDoc, "book");

To find elements by specifying multiple node names, use a pattern like this:

var nodes = PF.getNodes(xmlDoc, "book:author:firstname");

Page

blockUI(msg)

Dims the whole page, such that a popup or other overlay can be displayed.

If the msg parameter is specified, it displays a small dialog with a message inside it.

unblockUI()

Returns the page to its normal state.

Array Extensions

The Pageflake framework modifies the Array object prototype to provide several utility functions.

Array.add(item)

Adds the item to the end of the array.

Array.removeAt(index)

Removes the item at the specified position.

Array.indexOf(item)

Searches the array for the passed item and returns the
first index where the item is found. If the item is not found, -1 is returned.

Array.remove(item)

Searches the array for the passed items and, if found,
removes it from the array.

Array.contains(item)

Returns true if the items
exists in the array, false otherwise.

Array.find(func)

Evaluates the passed function for every item in the array and returns the first item that when passed as an argument to the function, makes the function return true.

If no items make the function evaluate to true, then null is
returned.

For example:

var item = someArray.find( function(item) { return item.a == 1; } );

Instead of:

var item;
for (var i=0; i < someArray.length; i++ )
{
  if( someArray[i].a == 1 )
   {
      item = someArray[i];
      break;
   }
}

Array.findIndex(func)

Evaluates the passed function for every item in the array and returns the first item that when passed as an argument to the function, makes the function return true.

If no items make the function evaluate to true, then -1 is returned.

Array.forEach(func)

Evaluates the passed function once for every item in the array passing two parameters each time. The first parameter is the item itself, and the second parameter is the array index where the item was retrieved from.

String Extensions

The Pageflake framework modifies the String object prototype to provide several utility functions.

String.trim()

Removes any leading and trailing whitespace.
String.toMapArray()

Converts the comma delimited string to an array.

ContentProxy

Most browsers don’t allow XMLHttpRequest to retrieve data from domains other than the domain where the script was fetched from, as shown in the diagram below.

ContentProxy1

Because of this security restriction, Pageflakes provides a content proxy server that can be used to fetch data from other domains. To do this, the flake makes a request to the proxy server. The proxy server then retrieves the content and returns it to the browser, as shown below.

ContentProxy1

The Content Proxy provides several methods:


ContentProxy.GetUrl(url, F(this, callbackFunction))
ContentProxy.FormPost(url, values, F(this, callbackFunction))
ContentProxy.UploadString(url, "content as string which is POSTed", F(this, callbackFunction));

If the call is successful, the content proxy invokes a function that was passed to it as callback.

The ContentProxy is set to cache any retrieved data for 10 minutes (GET calls only). Successive calls with the same parameters use the cached data rather than re-fetching the data from the remote server. This action optimizes flake performance. However, if updated data is required before the 15 minute interval, the GetURL or FormPost methods cannot be used.

Non-cached results can be retrieved using ContentProxy.getUrlNonCached(). The parameters are the same as ContentProxy.GetUrl().

HTTP GET Example

This code demonstrates the use of HTTP GET with the ContentProxy object:

ContentProxy.GetUrl("http://xml.example.com/", F(this, callback), onerror);

function callback(result)
{
// result is a string that can be used as needed
}
function onerror(exception)
{
}

HTTP POST Example

This example demonstrates how to pass POST parameters when using the ContentProxy object.

POSTData = {};
POSTData.parameter1 = "Some data";
POSTData.parameter2 = "Some more data";
ContentProxy.FormPost(url, POSTData, F(this, callback), onerror);
Alternatively, the following is also acceptable:
ContentProxy.FormPost(url, { parameter1 : “Some data”, parameter2 : “some more data” }, F(this, callback));

ContentProxyResponse

The ContentProxyResponse object is used by several of the ContentProxy functions to return headers and cookies, in addition to the returned content. This object has three properties:

Property Description
Content A string containing the content returned by the HTTP operation.
Header An array of objects, each representing an HTTP header. Each object has two properties: "Key" and "Value". "Key" is a string representing the name of the header, and “Value” is a string representing the value of the header.
Cookie An array of objects, each representing a cookie. Each object has two properties: "Key" and "Value". "Key" is a string representing the name of the cookie, and "Value" is a string representing the value of the cookie.


Header = [ { Key: “Content-Type” , Value: “foo”}, {Content-Length, “bar”] ]

GetUrl

Method signature

ContentProxy.GetUrl(url,succeededCallback, failedCallback)

Input Parameters

url

The URL of the target location.

 

succeededCallback

The function to invoked when the operation succeeds

 

failedCallback

The function to be invoked if the operation fails

Callback Parameter

Content of HTTP response as string.

Notes

The response is cached for 10 minutes.

GetUrl1

Method signature ContentProxy.GetUrl1(url, cacheDurationInMinutes, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  cacheDurationInMinutes Specifies how long the response is cached on the server.
  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter Content of the HTTP response as string.
Note The response is cached for the specified duration.

GetUrl2

Method signature ContentProxy.GetUrl2(url, headers, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  headers

An array of headers used to create the request object.

Each header object is a one-dimensional array having two elements. The first element is the name of the header and the second one is its value.

For example:

[ ["Content-Type","text/plain"], ["X-MyHeader","foo"] ]

  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter Content of HTTP response as string.
Note The response is cached for 10 minutes.

GetUrl3

Method signature ContentProxy.GetUrl3(url, headers, cookies, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  headers An array of headers used to create the request object.

Each header object is a one-dimensional array having two element. The first element is the name of the header and the second one is its value.

For example:

[ ["Content-Type","text/plain"], ["X-MyHeader","foo"] ]

  cookies An array of cookies used to create the request object.

Each cookie object a one-dimensional array having two elements. The first element is name of the cookie and the second one is its value.

For example:

[ ["session-id","1234"], ["other-cookie","foo"] ]

  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter A ContentProxyResponse object.
Note The response is cached for 10 minutes.

GetUrlNonCached

Method signature ContentProxy.GetUrlNonCached(url,succeededCallback,
failedCallback)
Input Parameters url The URL of the target location.
  succeededCallback The function that is invoked when the operation succeeds
  failedCallback The function that is invoked if the operation fails
Callback Parameter Content of HTTP response as string
Note The response will not be cached.

GetUrlNonCached2

Method signature ContentProxy.GetUrlNonCached2(url, headers, cookies, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  headers An array of headers used to create the request object.

Each header object is a one-dimensional array having two elements. The first element is the name of the header and the second one is its value.

For example:

[ [“Content-Type”,“text/plain”], [“X-MyHeader”,“foo”] ]

  cookies An array of cookies used to create the request object.

Each cookie object a one-dimensional array having two
elements. The first element is name of the cookie and the second one is its
value.

For example:

[ [“session-id”,“1234”], [“other-cookie”,“foo”] ]

  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter A ContentProxyResponse object.
Note The response is not cached.

FormPost

Method signature ContentProxy.FormPost(url, parameters, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  parameters Parameters that are passed with a given URL. The
parameters object basically is a dictionary which contains the parameters
name and value as key-value pair.
  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter The content of the HTTP response as a string.
Note FormPost method performs an HTTP POST operation.

FormPost2

Method signature ContentProxy.FormPost2(url, parameters, headers, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  parameters Parameters that are passed with the given URL. The parameters object is a dictionary which contains the parameters name and value as a key-value pair.
  headers

An array of headers used to create the request object.

Each header object is a one-dimensional array with two elements. The first element is the name of the header and the second is its value.

For example:

[ ["Content-Type","text/plain"], ["X-MyHeader","foo"] ]

  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter The content of the HTTP response as a string.
Note FormPost2 method performs an HTTP POST operation.

FormPost3

Method signature ContentProxy.FormPost2(url, parameters, headers, cookies, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  parameters The parameters passed to the given url. The parameters object basically is a dictionary which contains the parameter’s name and value as a key-value pair.
  headers

An array of headers used to create the request object.

Each header object is a one-dimensional array having two elements. The first element is the name of the header and the second one is its value.

For example:

[ ["Content-Type","text/plain"], ["X-MyHeader","uoo"] ]

  cookies An array of cookies used to create the request object.

Each cookie object is a one-dimensional array having two elements. The first element is the name of the cookie and the second one is its value.

For example:

[ [“session_id”,“abc123”], [“cart_status”,“foobar”] ]

  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter Content of HTTP response as string.
Note FormPost2 method performs an HTTP POST operation.

UploadString

Method signature ContentProxy.UploadString(url, requestData, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  requestData Data to be POSTed
  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter Content of HTTP response as string.
Note UploadString method performs HTTP POST operation and uploads the raw string to the specified URL. Useful for making SOAP calls.

UploadString2

Method signature ContentProxy.UploadString2(url, headers,
requestData, succeededCallback, failedCallback)
Input Parameters url The URL of the target location.
  headers An array of headers used to create the request object

Each header object is a one-dimensional array with two elements. The first element is the name of the header and the second one is its value.

For example:

[ ["Content-Type","text/plain"], ["X-MyHeader","foo"] ]

  requestData Data to be POSTed
  succeededCallback The function that is invoked when the operation succeeds.
  failedCallback The function that is invoked if the operation fails.
Callback Parameter Content of HTTP response as string.
Note UploadString2 performs an HTTP POST operation.

App

Pageflakes has a specific API to show content within a pop-up window. Pop-ups performed by this API are implemented as inline pop-up windows, not as a separate browser window.

Inline Browser

The App.showHtmlViewer function displays any external URL inside a small pop-up window. This function directly creates an inline window and displays the contents from the specified URL using IFRAME.

App.showHtmlViewer("Formula One", "http://news.bbc.co.uk/sport1/hi/motorsport/formula_one/default.stm");

Example

This example demonstrates the inline browser and popup functionality provided by the App object.

Popup Windows

You can use the App.createPopUp() function to create a display utilizing more control (such as specific HTML within the window). This function returns a reference to the newly created pop-up window.


var body = App.createPopup(id, title, left, top, width, height);
body.innerHTML = "anything you want"

This returns the body DIV inside which any content can be placed.

To load a page or a flake directly on a popup window, use this:


var body = App.createPopupPage(id, title, url, left, top, width, height)

This returns the body DIV.

Example

This example demonstrates the inline browser and popup functionality provided by the App object.

Compact Framework

When a flake is exported and placed on an external web site (i.e. not on pageflakes.com), it runs on a different, less functional version of the Pageflakes framework, also known as the Compact Framework. For example, you can’t use App.showHtmlViewer or create popup windows.

The following methods will not work in the Compact Framework:

FSO.resize()
FSO.close()
App.showHTMLViewer()
App.createPopup()
App.createPopupPage()

In addition, blockUI() and unblockUI() have a limited effect within the IFRAME that the flake is being displayed in.
Because of this, when a flake is running inside an IFRAME on a different website, those features should be turned off. The Compact Framework can be detected as follows:

if (App.IsCompactFramework)
{
//do necessary things for compact framework display
}

RSS

The Pageflakes API provides a number of functions that enable developers to retrieve and parse RSS feeds. These feeds are returned in the form of objects — the RSSChannel and RSSItem objects.

GetRSSChannel

Use the GetRSSChannel function to retrieve an RSS feed.

Method signature GetRSSChannel(string url, bool forceUpdate, int startIndex)
Input Parameters url URL of the feed
forceUpdate true: get from original source

false: get from server cache

startIndex Starting item number, used for paging. Default is zero, which retrieves the first 20 items in the feed.
Return Type RSSChannel
Notes

To retrieve the next page of 20 items, set the value for startIndex to 20, and so on.

The feed is cached for 10 minutes on both client and server.

GetRSSChannel2

Method signature GetRSSChannel2(string url, string[] extendedTags, int startIndex)
Input Parameters url URL of the feed
forceUpdate

true: get from original source

false: get from server cache

extendedTags

A string array of additional RSS tags to retrieve beyond the basic RSS tags such as <title> and <description>. For example, the Digg News flake uses the extendedTags parameter to retrieve the <digg:diggCount> value from Digg's RSS feed.
startIndex

Starting item number, used for paging. Default is zero, which retrieves the first 20 items in the feed.
Return Type RSSChannel

Notes

To retrieve the next page of 20 items, set the value for startIndex to 20, and so on.

The response is not cached on the browser.

Use GetRSSChannel3 or GetRSSChannel5 to control the number of items that are returned in a page.

GetRSSChannel3

Method signature GetRSSChannel3(string url, bool forceUpdate, int startIndex, int pageSize)
Input Parameters url URL of the feed
forceUpdate

true: get from original source

false: get from server cache

startIndex

Starting item number, used for paging. Default is zero, which retrieves the first 20 items in the feed.
pageSize Specifies the number of items to retrieve.
Return Type RSSChannel

Notes To retrieve the next page of 20 items, set the value for startIndex to 20, and so on.

GetRSSChannel4

Use GetRSSChannel4 to retrieve an RSS feed that requires authentication.

Method signature GetRSSChannel4(string url, string userName, string password)
Input Parameters url The URL of the RSS feed.
userName The user's user name.
password

The user's password.
Return Type RSSChannel

Use GetRSSChannel6 to retrieve an RSS feed that requires authentication with extended tags.

GetRSSChannel5

Use GetRSSChannel5 to retrieve an RSS feed, bypassing client-side caching.

Method signature GetRSSChannel5(string url, int startIndex, int pageSize, string key)
Input Parameters url URL of the feed
startIndex

Starting item number, used for paging. Default is zero, which retrieves the first 20 items in the feed.
pageSize Specifies the number of items to retrieve for paging purposes.
key

A unique key value used to bypass client-side caching. If you pass the same key within 10 minutes, the client will return the response from cache.

Return Type RSSChannel

Notes To retrieve the next page of 20 items, set the value for startIndex to 20, and so on.

GetRSSChannel6

Use GetRSSChannel6 to return an authenticated RSS feed with extended tags.

Method signature GetRSSChannel6(string url, string[] extendedTags, string userName, string password)
Input Parameters url URL of the feed
extendedTags

A string array of additional RSS tags to retrieve beyond the basic RSS tags such as <title> and <description>. For example, the Digg News flake uses the extendedTags parameter to retrieve the <digg:diggCount> value from Digg's RSS feed.
userName The user's user name.
password

The user's password.

Return Type RSSChannel

GetRSSChannels

Use the GetRSSChannels function to return two or more RSS feeds in a single call.

Method signature GetRSSChannels(string[] urls, int startIndex)
Input Parameters urls An array of RSS feed URLs to retrieve.
  startIndex

Starting item number, used for paging. Default is zero, which retrieves the first 20 items in the feed.
Return Type

RSSChannel[]

Notes

The method returns an array of RSSChannel objects.

Use the GetRSSChannels2 function to retrieve multiple RSS feeds containing extended tags.

GetRSSChannels2

Method signature GetRSSChannels2(string[] urls, string[] extendedTags, int startIndex)
Input Parameters urls An array of RSS feed URLs to retrieve.
  extendedTags

A string array of additional RSS tags to retrieve beyond the basic RSS tags such as <title> and <description>. For example, the Digg News flake uses the extendedTags parameter to retrieve the <digg:diggCount> value from Digg's RSS feed.

  startIndex Starting item number, used for paging. Default is zero, which retrieves the first 20 items in the feed.
Return Type RSSChannel[]
Notes

The method returns an array of RSSChannel objects.

RSSChannel and RSSItem Object Definitions

Pageflakes' RSS functions return RSS data in the form of objects — the RSSChannel object and the RSSItem object. Here are the definitions of these objects.

RSSChannel
{
  int ID;
  string Language;
  string Link;
  string Title;
  int TTL;
  string UrlHash;
  RSSItem[] Feeds;
  string FeedSource;
  string Description;
}

int RSSItem;
{
  int ID;
  string Title;
  string Description;
  string EncodedContent;
  string Link;
  string Guid;
  string Hash;
  DateTime PublishDate;
}

RSS Feed Example

This example shows how to use these APIs to fetch data from RSS feeds.


var feedUrl = _me.getFeedUrl();
RssServices.GetRSSChannel(feedUrl, true,0, function(channel))
{
  if(channel != null)
  {
    var feeds = channel.Feeds;
    if( feeds.length == 0 )
    {
      Alert( "No result found.");
    }
    else
    {
      for(i=0; i < feeds.length; i++)
      {
        title = feeds[i].title;
        description = feeds[i].description;
        link = feeds[i].link;
        // Do the rest by yourself
      }
    }
  }
};

Tooltip Manager

The TooltipManager object provides methods to handle mouse over and mouse out events properly to facilitate the creation of tooltips. There are two functions:

TM.setTooltip(element, tooltipText);
TM.setTooltipNow(event, element, tooltipText, delay);

The first function automatically adds the correct event handlers and shows the tooltip when the mouse is over the specified element. As such, this function should be called on initialization, and not on mouseover.

For example:

TM.setTooltip( textInputElement, 'Hi this is a tooltip' );

Tooltip

The second function immediately shows the tooltip. To use this, the correct event handler needs to be attached. For example:

PF.addEvent('somebutton', 'mouseover', callback);
function callback(e)
{
TM.showTooltipNow(e, this, 'Hi! This is a tooltip', 500);
}

Public, Shared, and Private Pages

Pageflakes users can select one of three levels of access for their pages:

Flakes need to be aware of the type of user (owner, shared, public) accessing the flake and correctly set their behavior. For example, a “notepad” flake that lives on a public page should only allow the owner to make changes. Conversely, a “guest-book” flake that lives on a public page should allow anyone to make changes to its content.

To solve this problem, Pageflakes provides four types of profiles. Each profile is associated with specific access permissions. In addition, Pageflakes provides functions that the flake can use to determine the current user’s access level, so an appropriate user interface can be displayed.

  Owner Shared Public
Profile RW RW1 R
PrivateProfile RW - -
PublicProfile RW RW RW
VisitorProfile

Readable and writable only by the current visitor.

To determine the access level of the current user the flake can use the following methods:

fso.page.IsOwner True if the user is the owner of the page, and therefore determines if the user can write to the Profile and PrivateProfile.
fso.CanChangeFlake Returns true if the flake is shared to this user, and therefore determines if the user can write to the Profile.

Server-Side Scripting

The Pageflakes framework generates the following HTTP headers when fetching a Flake. Flakes that utilize server-side scripting can use these headers as needed.

Accept Type of content Pageflakes expects from your script. If the received Content-Type does not match this field, then the content is discarded.
Accept-Encoding Currently only supports gzip encoding.
Accept-Language Original Accept-Language header that was reported to Pageflakes by the requesting user agent. This header can be used to determine the browser’s language.
Host IP address of the Pageflakes server. This is within the IP range: 69.5.89.XXX. Flakes should verify this IP address to ensure that the data that is passed in the UserGUID parameter can be trusted.

If the IP address does not match, this means that the flake is being accessed by a non-Pageflakes server, and the flake is then responsible for authenticating the request and not releasing any sensitive data until the access level of the requester has been ascertained.

User-Agent Agent string identifying the Pageflakes agent making the request.

UserAgent User-Agent header that was reported to Pageflakes by the requesting user agent.

InstanceId Unique ID of the flake instance.
FlakeUrl URL of the flake with query string. This is the URL of the flake instance that was used to add the flake.

For example, a single URL may implement two flakes:


http://www.example.com/myflake.aspx?flake=A
http://www.example.com/myflake.aspx?flake=B

A more likely example might have the News flake and the Weather flake share some code:


http://www.example.com/flake.aspx?content=news
http://www.example.com/flake.aspx?content=weather

This parameter can be used by the flake to determine any specific behavior.

HostIP IP address reported to Pageflakes by the requesting Browser.
UserGUID Internal GUID of the Pageflakes user. This can be used in combination with the InstanceId to maintain session state.

Example:

Accept: text/html, text/xml, text/plain, application/json, ...
Accept-Encoding: gzip
Accept-Language: en-us
Host: 69.5.89.XXX:1167
User-Agent: Pageflakes/1.0 (WinNT 5.1.2600.0; http://www.pageflakes.com)
UserAgent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;
InfoPath.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; FDM)
InstanceId: m90629
FlakeUrl: http://www.example.com/yourapp/yourflake.php
HostIP: 127.0.0.1
UserGUID: 983b4547-78ae-423e-aae9-13aa47c5d657