Injecting Web Page Behavior

,

On occasion you may want to invoke some JavaScript on a third-party web page, in which case relying on a named JavaScript function becomes impossible. Fortunately, JavaScript’s eval function gives us the power to execute arbitrary JavaScript.


Note

Be aware that it is possible to override the JavaScript eval function, which may result in less than complete reliability for the technique presented in this section. Overriding eval is, however, rare, and web pages that do this do not comply with the ECMAScript 5 specification.


To demonstrate the execution of arbitrary JavaScript, another button has been added to the WebBrowserWithScriptingView.xaml page. Clicking the button causes a script to be invoked on the web page, which identifies all the hyperlinks on the page and attaches a client-side event handler to each anchor’s onclick event, as shown in the following excerpt:

void Button_InjectScript_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
    webBrowser.InvokeScript("eval", evalScript);
}

const string evalScript
    = @"var anchors = document.getElementsByTagName('a'),
    for(var i = 0; i < anchors.length; i++)
    {
        var anchor = anchors[i];
        anchor.attachEvent('onclick', function()
            {
                anchor.innerHTML = 'This text was changed by attaching'
                                 + ' an event handler from the app!';
            });
    }";

,

This script executes client-side, after which, when the user clicks a link, the link’s text is changed. It is a wacky example, yet we see that the eval function gives us the power to manipulate any part of the web page’s Document Object Model (DOM). It could be used, for example, to highlight keywords on a web page or modify styles on a web page that you did not create.

Figure 7.16 shows the updated PhoneApplication page and the ordered steps for executing the JavaScript.

Image

FIGURE 7.16 Injecting web page behavior at runtime from .NET.

After the script is invoked, clicking the link causes an event handler to be called within the web page, where the style of the link is modified (see Figure 7.17).

Image

FIGURE 7.17 The anchor style is modified via an injected JavaScript event handler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.139.87