Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Aug
24
2012

How to Use iFrames in WinRT Apps

SNAGHTML25abaef5Did you know you could use iFrames in WinRT apps developed using JavaScript?  Is this suppose to be exciting?  Why would you care?  For the answers, follow along as I take a journey of discovery attempting to add live Twitter feeds to my app.

To set the stage for what I want to do, you must first understand what a Twitter Widget is.  The folks at Twitter have made it real easy for web developers to create a custom, dynamic section of a web site to display tweets based on a user, a search, favorites, or a list.  Once I know my tweet criteria, I can customize the appearance, dimensions, and other relevant options.  When I am done with all my customizations, I can grab the code that will make the magic happen on my web site.  Um… but I want this in my WinRT app.  Will it work?  Lets find out.

I will choose to create a Twitter Search Widget.  Here is a screen capture of my criteria:

SNAGHTML25bbc55e

Once I click the [Finish & Grab Code] button, I see the following:

SNAGHTML25be0be3

Now I will add this code to my project in Visual Studio 2012.  I have just created this project using a blank template. In the default.html file, I will add the Twitter widget code I created above.  Here is what my markup looks like:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>HowTo_IFrames</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- HowTo_IFrames references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    <p>Content goes here</p>
    <script charset="utf-8" 
            src="http://widgets.twimg.com/j/2/widget.js"></script>
    <script>
            new TWTR.Widget({
            version: 2,
            type: 'search',
            search: '#win8appdev',
            interval: 30000,
            title: 'Windows 8 Developers',
            subject: '#win8appdev',
            width: 250,
            height: 300,
            theme: {
                shell: {
                    background: '#8ec1da',
                    color: '#ffffff'
                },
                tweets: {
                    background: '#ffffff',
                    color: '#444444',
                    links: '#1985b5'
                }
            },
            features: {
                scrollbar: false,
                loop: true,
                live: true,
                behavior: 'default'
            }
        }).render().start();
    </script>
</body>
</html>

Will it be that simple?  Unfortunately no.  When I attempt to run the application, I get the following error:

SNAGHTML25cae34d

It may not be obvious by the error message what the real issue is.  The reason why ‘TWTR’ is undefined is due to the following script not being executed:

<script charset="utf-8"             
        src="http://widgets.twimg.com/j/2/widget.js"></script>

Why did the script not execute?  Because my default.html page is considered local in context to my application.  The only way an external script would be allowed to execute is if it was executed in a web context.  Well who decided those rules?  Perhaps a better question for now is – How do I know if I am in local context or web context?

Any HTML file that is physically part of a project is considered as local in context. The converse to this is any HTML that resides externally or is remote to a project is considered to be in web context.  How can I execute HTML remotely in my WinRT app?

Using iFrames

I can use an iframe in my HTML to point to an external web page.  To demonstrate, I will remove the script I added to my default.html page (we will return to that code later), and replace the contents of the body tag with the following:

<h1>iFrame Demo</h1>
<iframe src="http://www.palermo4.com"
        width="900"
        height="600">
</iframe>

When I run my application now, this is what I see:

image

If this is all I do, I essentially have a “browser” to my site within my app.  I could also change the source of the iFrame from anchor tags as seen with the following revisions:

<h1>iFrame Demo</h1>
<div>
    <a href="http://palermo4.com" target="framed">Palermo4</a> 
    <a href="http://codefoster.com" target="framed">Codefoster</a>
</div>
<iframe name="framed" width="900" height="600">
</iframe>

This will cause the iFrame to load the respective href value once either of the anchor tags are clicked.

Recommended:  Create an HTML file in the root directory of your project named
msapp-error.html.  This file will be loaded automatically in the iframe when errors occur due source resources not loading or not found!

Now returning to my original objective, I would like to see the code I grabbed from Twitter work in my app still.  I have an idea!  I will take Twitter widget code and put in in a new HTML file in my project.  I will name the file twitterframe.html, and create it in the root project directory.  Here is the contents of that file:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <script charset="utf-8" 
                src="http://widgets.twimg.com/j/2/widget.js">
        </script>
    <script> 
        new TWTR.Widget({
            version: 2,
            type: 'search',
            search: '#win8appdev',
            interval: 30000,
            title: 'Windows 8 Developers',
            subject: '#win8appdev',
            width: 250,
            height: 300,
            theme: {
                shell: {
                    background: '#8ec1da',
                    color: '#ffffff'
                },
                tweets: {
                    background: '#ffffff',
                    color: '#444444',
                    links: '#1985b5'
                }
            },
            features: {
                scrollbar: false,
                loop: true,
                live: true,
                behavior: 'default'
            }
        }).render().start();
    </script>
    </body>
</html>

Now I will return to default.html, and modify the contents within the body tags as follows:

<h1>iFrame Demo</h1>
<iframe src="/twitterframe.html" width="300" height="400">
</iframe>

Will I get my desired output?  Can I trick the iframe to run a page in local context but treat it like it is in web context?  Not the way I am doing it.  When I run my application, I get the same error I received earlier.  However, I was on the right track of thinking.  By using a special moniker preceding the URL, I can ask for the local page to be executed in a web context.  Here is the syntax for that:

<iframe src="ms-appx-web:///twitterframe.html" 
        width="300" height="400">
</iframe>

By adding ms-appx-web:/// before my local page name, I am informing my application to run it in a web context. This crucial step gives me exactly what I want, as seen here:

image

Hooray!  I got my Twitter search widget to work in my WinRT app!  Think of the possibilities with any other social meshing sites or mapping tools!

By the way, you can govern what is allowed to happen in the iFrame by setting the sandbox attribute.  IntelliSense reveals self-describing features:

SNAGHTML261ce5af

I hope you enjoy developing Windows 8 applications with JavaScript and HTML5!  For more resources, be sure to sign up for Generation App! Your idea. Your app. 30 days.

Cheers!

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Jul
13
2012

Code Samples for JavaScript Metro Style Apps

What do most developers want when they need to learn something new?  Most of us want code samples, and feature-targeted ones at that.  Thank goodness you will not have to endlessly search  for Metro style app samples via JavaScript.  If you have downloaded a flavor of Visual Studio 2012, the samples are closer than you may have expected.

Update!

Be sure to checkout the developer center download page for more samples!

The “New Project” dialog box in Visual Studio provides an option to easily access samples as seen in the following screen capture:

javascript-metro-samples

Underneath the “Online” option on the left side of the box, there is a “Samples” option with choice of language. In this example, I chose JavaScript.  Notice the first glimpse of app features just waiting for you to choose. 

Upon selecting a sample, you will get the following dialog box with standard disclaimers:

splash-sample-install

After clicking the “Install” button, the sample you selected will be loaded into solution explorer.  A description page (downloaded as a solution item) will be displayed as seen here:

splash-desc

The sample is ready to go!  You can poke around (code is pampered with comments) or run it immediately.

The main message here is this – before you go searching the web all over for that “how to” sample, you might be pleasantly surprised to see it is already available via Visual Studio 2012!

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Apr
13
2012

JavaScript RegEx Pattern for URLs

Here is a simple JavaScript RegEx pattern for extracting any URL that begins with http:

<script type="text/javascript">

// example string, looks like a tweet to me :)
var str="Awesome resources for HTML5! http://bit.ly/palermo4html5 #HTML5";

// UPDATED 2012-07 thanks to ArthurDent69!
// could also be written as:
// var regexUrl = new RegExp("https?:[^\s]+", "gi");
var regexUrl=/https?:[^\s]+/gi;

// if a match is found, the return type is an array of matches
document.write(str.match(regexUrl));

// output of above line of code:
// http://bit.ly/palermo4html5

</script>
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Feb
6
2012
css // css3 // code // javascript

CSS3 Colors–HSLA to RGBA

In my previous post on CSS3 Colors – RGBA vs. HSLA, I provided a script to easily convert RGB to HSL using inputs/outputs friendly to CSS3.  In this post, I provide the reverse script – converting from HSL to RGB.  The trailing “A” means Alpha (scale of opacity), and requires no conversion.

// elsewhere in script use this way:
// var result = Palermozr.hslToRgb(0,0,100);
// result.R // Red
// result.G // Green
// result.B // Blue
var Palermozr = (function () {
    function hslToRgb(h, s, l) {
        h /= 360; s /= 100; l /= 100;
        var r, g, b;
        if (s == 0) {
            r = g = b = l;
        } else {
            var l2 = l < 0.5 ? l * (1 + s) : (l + s) - (s * l);
            var l1 = (2 * l) - l2;
            r = hueToRgb(l1, l2, (h + (1 / 3)));
            g = hueToRgb(l1, l2, h);
            b = hueToRgb(l1, l2, (h - (1 / 3)));
        }
        r = Math.round(255 * r);
        g = Math.round(255 * g);
        b = Math.round(255 * b);
        return { R: r, G: g, B: b };
    }
    // helper function used above
    function hueToRgb(l1, l2, h) {
        if (h < 0) h += 1;
        if (h > 1) h -= 1;
        if (h < 1 / 6) return (l1 + (l2 - l1) * 6 * h);
        if (h < 1 / 2) return l2;
        if (h < 2 / 3) return (l1 + (l2 - l1) * ((2 / 3) - h) * 6);
        return l1;
    }

    return {
        hslToRgb: hslToRgb
    };
})();
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Feb
3
2012

CSS3 Colors–RGBA vs. HSLA

hslThere really is no battle between RGBA and HSLA.  Either can accomplish the task of discovering the color that is just right for you.  Which should you choose?  Which is an easier concept for you to understand?

Red
Green
Blue

Hue
Saturation
Lightness

Alpha (opacity)

 

Again, which above is easier for you to understand?

According to the W3C:

4.2.4. HSL color values

CSS3 adds numerical hue-saturation-lightness (HSL) colors as a complement to numerical RGB colors. It has been observed that RGB colors have the following limitations:

  • RGB is hardware-oriented: it reflects the use of CRTs.
  • RGB is non-intuitive. People can learn how to use RGB, but actually by internalizing how to translate hue, saturation and lightness, or something similar, to RGB.

Is RGB truly non-intuitive?  By looking at the color wheel in this post would it be intuitive for you to know the hue value of 1 or 360 is red?  Which is easier to digest:  blue=blue or 240=blue.

It doesn’t really matter.  What really mattered to me was to understand the algorithm to convert from one to another.  Since alpha is simply a scale of opacity, I was more curious about the conversion of red, green, and blue to something light, saturated, and with hue.

To test my understanding, I set out to write a script that was CSS3 friendly.  In other words, it would use as inputs/outputs values used in the rgba() and hsla() functions in CSS3.  The result is the script below. 

As always, I value feedback Smile

// elsewhere in script use this way:
// var result = Palermozr.rgbToHsl(255,255,255);
// result.H // Hue (between 1 and 360)
// result.S // Saturation (between 0 and 100) %
// result.L // Lightness (between 0 and 100) %
var Palermozr= (function () {
    function rgbToHsl(r, g, b) {
        r /= 255;g /= 255;b /= 255;
        var max = Math.max(r, g, b),
            min = Math.min(r, g, b);
        var d = max - min,
            u = max + min;
        var h = 0, s = 0, l = u / 2;
        if (d !== 0) {
            s = l < 0.5 ? d / u : d / (2 - d);
            var rr = (((max - r) / 6) + (max / 2)) / d;
            var gg = (((max - g) / 6) + (max / 2)) / d;
            var bb = (((max - b) / 6) + (max / 2)) / d;
            switch (max) {
                case r: h = (bb - gg); break;
                case g: h = (1 / 3) + (rr - bb); break;
                case b: h = (2 / 3) + (gg - rr); break;
            }
            if (h < 0) h += 1;
            if (h > 1) h -= 1;
            h = Math.round((h * 360));
        }
        s = Math.round(s * 100);
        l = Math.round(l * 100);

        // returns object with H,S, and L property values
        return { H: h, S: s, L: l };
    }
    
    return {
        rgbToHsl: rgbToHsl
    };
})();
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Feb
2
2012

Feature Detection Script for CSS3 Selectors

If you are a serious HTML5|CSS3 developer, you have undoubtedly come across the amazing resource known as Modernizr.  Modernizr is an amazing suite of script functions that enable feature detection to provide intelligent rendering across the multiple browsers that do or don’t support the desired feature.

Recently I was in need of a specific feature detection in CSS3 that I realized was not in the latest version of Modernizr – the ability to detect support for CSS3 Selectors.  Some examples of new CSS3 selectors include:  ::selection, :root, :target, :not, :checked, :empty … just to name a few. With necessity being the mother of invention, I took it upon myself to create the script needed to do the job. 

Here is the script, and I look forward to any feedback Smile

// elsewhere in script use this way:  
// var result = Palermozr.isSelectorSupported(":root");
var Palermozr = (function () {
    function isSelectorSupported(anySelector) {
        var newStyle = document.createElement("style"),
                cssRule = anySelector + "{}",
                isSupported = false,
                styles,
                rules,
                selectorText;
        newStyle.type = "text\/css";
        if (newStyle.styleSheet) {
            styles = newStyle.styleSheet;
            if (styles.cssText) {
                styles.cssText = cssRule;
                if (styles.rules) {
                    rules = styles.rules;
                    if (rules[0].selectorText) {
                        selectorText = rules[0].selectorText.toLowerCase();
                        isSupported = selectorText.indexOf("unknown") < 0;
                    }
                }
            }
        } else {
            newStyle.appendChild(document.createTextNode(cssRule));
            document.body.appendChild(newStyle);
            isSupported = !!newStyle.sheet.cssRules.length;
            document.body.removeChild(newStyle);
        }
        return isSupported;
    }
    return {
        isSelectorSupported: isSelectorSupported
    };
})();
    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
Nov
10
2011

HTML5 Web Camp Videos

The highly popular HTML5 Web Camp events sponsored by Microsoft are typically filled to capacity when delivered at any location.  In my humble opinion, the best HTML5 Web Camp delivered to date was in my hometown of Phoenix, AZ.  Fortunately, the team at EventDay showed up that day to record every session.  With great pleasure, I announce the availability of these videos for you to watch at your convenience – for free!

video-callouts

Each video provides a simple user interface that allows you to see the presenter, the content on the screen, and navigation controls to the topic you are most interested in.  When the screen in maximized, you will truly be immersed into the experience as if you attended live!

 

 

The link for all these videos is found below.  Please share with your community!!!

http://bit.ly/html5camp-videos

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).

Resources

Archives

Team Blogs

Download OPML file OPML