Home  >  Article  >  Web Front-end  >  Building Windows Store apps using jQuery 2.0

Building Windows Store apps using jQuery 2.0

WBOY
WBOYOriginal
2023-09-02 13:33:05698browse

使用jQuery 2.0构建Windows Store应用程序

With the release of Windows 8, Microsoft introduced Windows Store apps that can be written in traditional web languages ​​and leverage the underlying engine that powers Internet Explorer 10. This means jQuery 2.0 is designed to run best in modern browsers and is the right Windows Store app to use at home!


Understanding the context

Windows Store apps are different from the web and have two different contexts, local and web. Because code in the local context can access Windows Runtime APIs, a new security model is required.

For best results, you will download jQuery and load it into a local context. Attempting to load from a remote location (such as a CDN) will result in a message similar to "The application cannot load remote web content in the local context."


Understanding “unsafe” code

DOM manipulation is one of the biggest changes you encounter when using jQuery in Windows Store apps compared to the browser.

On the web, it's not uncommon to add elements to a form by passing an HTML string to jQuery's .append() method:

$("#form").append("<input name='foo' value='bar' />");

In a Windows Store app that has easy access to the user's computer, the stakes are much higher, and a lot of things you may be used to doing need to be rethought. The above is considered unsafe due to the name attribute. There are many other elements, attributes, protocols, etc. that are considered unsafe.

For a detailed list of safe and unsafe, see Making HTML Safer: toStaticHTML for details.

This does not mean that you cannot programmatically populate a container with dynamic items; it does mean that you cannot programmatically populate dynamic items into a container. You just have to take a slightly different approach. For example, you can use jQuery to create the input element itself instead of passing it in a string:

$("<input>", { name: "foo", value: "bar" }).appendTo("#form");

In the example above, you create an input element using jQuery's html, attribute signature. This indicates to the security model that you have complete control over the element, its attributes, and their corresponding values. This pattern also works in the browser and has been present in jQuery since version 1.4.


Clean up potentially unsafe content

When receiving content from a remote endpoint, it is wise to sanitize it before placing it into the DOM. You can do this in a number of ways using helper functions, such as toStaticHTML, which removes all dynamic items from the string.

Suppose you wish to request a string of tokens from a remote service that includes a greeting for the current user. It's entirely possible that the service could be tampered with and actually return more content to our application than you might expect.

In the code below you will see that the hidden form field has appended itself to the response.

<h1>Hello, Dave.</h1><input name='id' value='a528af' type='hidden' />

Injecting this into a form can have disastrous consequences. Therefore, you should first pass it via toStaticHTML to clear any elements, attributes, or values ​​that can be used to manipulate form data or perform other unapproved actions.

$("#greeting").html(toStaticHTML(response));

When the method sees our input element tag, it will identify and remove the dynamic name attribute, thus preventing any unexpected data from entering the form submission. For a more detailed look at what can and cannot be preserved in the toStaticHTML method, see Making HTML Safer: toStaticHTML for details.


When you know best

Sometimes you inevitably need to do something that may seem unsafe. For example, you might want to use a piece of HTML as a template to build a new element. In these situations, Microsoft provides methods that you can use when necessary and when you are confident that what you are doing does not put users at risk.

On the global MSApp object in a Windows Store app, the execUnsafeLocalFunction function exists and does exactly what it suggests: allowing you to execute on a case-by-case basis Unsafe function. Maybe you want to add an input field to edit the username, our code might look very similar to the previous example:

<h1>Hello, <input name="id" value="Dave" /><h1>

We can assign it to the innerHTML attribute via an anonymous function:

MSApp.execUnsafeLocalFunction(function () {
    $("#greeting").html(response);
});

Within the scope of this feature, you can step outside the security model and perform other unsafe operations without being second-guessed by the environment. It should be fairly obvious why this method should be used with caution.

There are also some utility methods under

WinJS.Utilities in Windows Store apps for performing similar tasks. They are setInnerHTMLUnsafe and setOuterHTMLUnsafe. Like execUnsafeLocalFunction, these should also be used with caution and when you don't want to risk using data that is beyond your control.

这些实用函数将您想要操作的 DOM 元素以及您想要分配的字符串作为参数。

WinJS.Utilities.setInnerHTMLUnsafe( $("#greeting").get(0), response );
WinJS.Utilities.setOuterHTMLUnsafe( $("#greeting").get(0), response );

这里的区别在于 setInner 替换了元素的 innerHTML ,而 setOuter 替换了元素本身 - 想想 jQuery 的 replaceWith 方法。对于这两个函数,您只需传入对 DOM 元素和我们所需的 innerHTML 的引用即可。


兼容性说明

在上一节中,您介绍了两个对象,即包含 execUnsafeLocalFunction 函数的 MSApp 对象,以及包含两个实用函数 setInnerHTMLUnsafesetOuterHTMLUnsafeWinJS 对象。

这些对象仅存在于 Windows 应用商店应用程序中,而不存在于您的浏览器中(除非某人或某物创建了类似名称的对象)。如果您希望编写既可以在 Windows 应用商店环境又可以在浏览器中运行的代码,则需要先检查这些对象,然后再推测它们的存在。

var $greeting = $("#greeting");

if (typeof WinJS !== "undefined" && WinJS.Utilities) {
    WinJS.Utilities.setInnerHTMLUnsafe($greeting.get(0), response);
} else {
    $greeting.html(response);
}

在 Windows 应用商店应用程序中,上述代码将使用 WinJS.Utilities 方法来执行分配。当在 WinJS 未知的环境中运行时,例如在 Web 浏览器中,代码将通过 jQuery 的 .html 方法执行分配。


不再有同源问题

利用远程服务的能力是网络变得伟大的一部分。在传统浏览器中,您会遇到起源问题,这导致了 JSONP 等解决方案的出现,并最终出现了 CORS。由于 Windows 应用商店应用程序在操作系统上运行,因此来源无关紧要。

$.ajax("http://api.twitter.com/1/statuses/user_timeline.json", {
    data: { screen_name: "appendTo" },
    success: function (data) {
        $("<img>", { src: data[0].user.profile\_image\_url }).appendTo("body");
        $.each(data, function (key, tweet) {
            $("<p>").text(tweet.text).appendTo("body");
        });
    }
});

上面的内容从 @appendTo 帐户获取所有最新推文,并将每条推文包装在自己的段落标记中,并将个人资料图像放在它们上方。在 Windows 应用商店应用程序中,无需使用 script 标记、设置标头或通过服务器端脚本进行代理即可实现此目的。


结论

虽然本文并不详尽,但它确实提供了您在 Windows 应用商店应用程序中快速启动并运行 jQuery 所需的初始动力。玩得开心!

The above is the detailed content of Building Windows Store apps using jQuery 2.0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn