Home > Web Front-end > JS Tutorial > Hosting IFRAMES_jquery using the JQUERY Tabs plugin

Hosting IFRAMES_jquery using the JQUERY Tabs plugin

WBOY
Release: 2016-05-16 18:37:30
Original
994 people have browsed it

Necessary things:

Windows XP/Vista/7/2003/2008
Visual Studio 2005 or 2008 (download the correct version of Home Site project above)
.NET Framework 2.0 and ASP.NET AJAX 1.0
Today, many browsers provide the ability to use tabs to browse more web pages and websites. Of course this is a very useful feature to replace having several browsers open at the same time, but it would also be great if it provided the ability to browse multiple web pages in one page.

For example, if your homepage is made up of many different useful web tools or sites, a tab page may be very useful. Using framesets, IFRAMEs, etc. are typical ways of hosting external content. These methods allow you to host multiple web pages on a single page. But getting them laid out correctly is not easy. Not to mention dealing with issues such as page and IFRAME scrollbars.

In this article, we try to host external data and provide a basic solution, using ASP.NET, AJAX and javascript to deal with some troubles encountered.

Plan

The main purpose is to provide a simple solution for hosting external data. This solution has the following simple requirements.

1. Provide a tab interface for easy browsing.

2. Provide a configuration method to add tabs

3. Enable each tab page to host a configured page

The basic technical requirements are:

1. Load external data content only when the tab is selected

2. Ensure that the vertical scrollbars are set to display, and only when the data that needs to be processed overflows, the scrollbars are displayed.

3. Ensure that the solution can work across browsers

The name of the solution and the name of the main page are both Home Site

Analysis

For this solution, I decided to use JQuery UI Tabs to implement tabular navigation functionality. I have also used commercial open source tab controls before. But JQuery UI Tabs are lightweight, very simple to implement, and free.

Except JQuery and tab controls and the functions provided by .net, no other controls are needed. VS2005 will be enough to combine the development environment of the entire project and choose C# as the development language.

I will be using an IFRAME to host the website content, using JQuery UI Tabs to host external web pages will not work directly due to cross-site (aka cross-domain) security restrictions.

Design

Here is a visual minimum requirement for the client:

This solution will require three different functional modules:
1. Configuration module
2. Use the tab interface of the JQuery UI Tabs plug-in
3. Use the IFRAME element to host web page content.
Configuration module:
A required feature is to make tabs configurable. I chose the minimum and put the tab configuration information into an xml file. Although I could go a step further and enable the dynamic addition and deletion of tabs, I decided to provide this functionality in the second part of this article.
The format of the XML file is as follows:
Code

Copy code The code is as follows:







Parameter description:
id = the unique ID of the tab. This ID cannot contain spaces
displayName = the name displayed in the tab header
path = URL with query parameters, "http://" is optional.
The name of the configuration file is: TabConfig.xml. You must now manually add or remove tabs to update the solution's configuration file.
Content loader:
It can be said that if there is no content loading module, IFRAME is needed to set internal list items for the tab page. But if the IFRAME is in a separate host web page by using anchors as child elements of each tab list element, I think there is no better control than IFRAME in terms of functionality and testing:

If you want, make the content loader a generic module that accepts query string parameters to properly set up the IFRAME element; the parameters are the element's unique ID, and the source attribute value, which is the URL of the page being loaded.

Another design requirement of the content loader is that the IFRAME must load the entire page (scrolling is set to auto). Additionally, the page body must hide overflow (by setting style attributes) to avoid duplicate scrollbars. Especially when changing the browser size. Finally, scrollbar handling must be cross-browser.

tab interface

tab interface code is very simple. You can get detailed demonstration code from the JQuery UI Tabs documentation. The difference between the JQuery UI Tabs documentation and the specific implementation of our JQuery UI Tabs is that the href of each tab item anchor points to the content loading page, and then loads the required web page into the IFRAME.

Some extra stuff

Tag above, I think it would be convenient to use a div to display header, logo, or even some links or menu items. As a better requirement, I want the header to be foldable so that the page hosted by each tag can have a maximum visual effect.

The final design layout is as follows:

Code/Development
We start with the content loader, here is the markup:
Code
Copy code The code is as follows:

<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind= "ContentLoader.aspx.cs" Inherits="HomeSite.ContentLoader" %>


ContentLoader








runat="server">

The place is the css code. I set the margin of the body to 0 and set the overflow to hidden. Prevent scrollbars from appearing on the body of the page.
IFRAME's scrolling is set to auto, so if a scroll bar is needed, only IFRAME provides it. Because there is a lot of unsightly white space around the IFRAME, margins are also set to 0, and the height and width of the IFRAME are set to 100% to ensure that the web content takes up as much space as possible. Please note the use of Literal controls in the html tag. As you'll see in the code-behind below, the purpose of using Literal is to allow the code-behind to inject stuff into the IFRAME element, which will construct the correct querystring's ID and Path parameters.
Code




Copy code
The code is as follows:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace HomeSite
{
///
/// Content Loader code behind class
///

public partial class ContentLoader : System.Web.UI.Page
{
///
/// On Page Load we need to capture query string parameters, construct
/// an IFRAME element, and inject the IFRAME element into our Literal control
///

///
///
protected void Page_Load(object sender, EventArgs e)
{
string id = "";
string path = "";
// Validate we have valid querystring parameters
// namely "ID" and "Path"
if (HasValue(Request["ID"]) &&
HasValue(Request["Path"]))
{
// Set our local variables
id = Request["ID"].Trim().ToString();
path = Request["Path"].Trim().ToString();
// Prepend the path URL with http:// if needed
if (!path.ToLowerInvariant().StartsWith("http://"))
path = "http://" path;
// Construct the IFRAME element and set the Text value of the Literal control
Literal1.Text = "";
}
else
{
// Either query parameter or both are not set or do not
// exist (not passed as request parameters)
Literal1.Text = "An "
"error occurred while attempting to load a web page.
";
}
}
///
/// Simple static class used to validate the value of querystring
/// parameter is not null or an empty string
///

/// The object to check
/// Returns true if the object (string)
/// has a value; false otherwise.

public static bool HasValue(object o)
{
if (o == null)
return false;
if (o is String)
{
if (((String) o).Trim() == String.Empty)
return false;
}
return true;
}
}
}

只要你将querystring的ID和Path参数传递给它,装载的页面能够单独的运行。通过VS2005浏览网页,有URL的示例:http://localhost:49573/ContentLoader.aspx?ID=1234&Path=www.amazon.com.
复制代码 代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Text;

namespace HomeSite
{
    ///


    /// Tab configuration static handling class
    ///

    public static class TabConfiguration
    {
        ///
        /// This class returns a collection of TabDefinition classes created from
        /// parsing the tab definitions defined in the TabConfig.xml file.
        ///

        /// The Page reference
        ///         calling this class
        /// ArrayList of TabDefinition classes
        public static ArrayList LoadConfiguration(Page page)
        {
            // Local container for tab definitions
            ArrayList tabList = new ArrayList();

            try
            {
                // Read the contents of the TabConfig.xml file
                StreamReader reader = new StreamReader(new FileStream(
                   page.MapPath("./TabConfig.xml"),
                   FileMode.Open, FileAccess.Read));
                string xmlContent = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                // Create an XML document and load the tab configuration file contents
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlContent);

                // Iterate through each tab definition, create a TabDefinition class,
                // and add the TabDefinition to the local ArrayList container

                foreach (XmlNode node in xmlDoc.SelectNodes("/configuration/tab"))
                {
                    TabDefinition tab = new TabDefinition();
                    tab.ID = node.Attributes["id"].Value;
                    tab.DisplayName = node.Attributes["displayName"].Value;
                    tab.Path = node.Attributes["path"].Value;
                    tabList.Add(tab);
                }
            }
            catch
            {
                // Do nothing
            }

            // Return the tab definition
            return tabList;
        }
    }

    ///


    /// This class serves as the container for a tab definition
    ///

    public class TabDefinition
    {
        ///
        /// Member variable for the Unique ID for the tab
        ///

        private string _id;

        ///


        /// Member variable for the displayed name of the tab
        ///

        private string _displayName;

        ///


        /// Member variable for the web page URL to host in the tab (IFRAME)
        ///

        private string _path;

        ///


        /// Property for the Unique ID for the tab
        ///

        public string ID
        {
            get { return _id; }
            set { _id = value; }
        }

        ///


        /// Property for the displayed name of the tab
        ///

        public string DisplayName
        {
            get { return _displayName; }
            set { _displayName = value; }
        }

        ///


        /// Property for the web page URL to host in the tab (IFRAME)
        ///

        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }
    }
}


Please note that the page instance must provide the LoadConfiguration method to correctly introduce the location of TabConfig.xml. I could have used XmlTextReader, but chose to use StreamReader to read the contents of the entire configuration file and use the XmlDocument object to parse the tab configuration information. Because I think it is much better to quickly dump the entire configuration file than to open the configuration file through process parsing. This is exactly the case using XmlTextReader.

Now, let’s take a look at the markup of the Home Site’s homepage

Code

Copy code The code is as follows:

<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="HomeSite._Default" %>

http://www.w3.org/1999/xhtml">

    Home Site
    type="text/css" rel="stylesheet" />
    type="text/css" rel="stylesheet" />
   
   
   
   



   

       
       

           
               
                   
               
               
                   
               
           
                             valign="top" align="left">
                       

                           
                                    class="tabs" runat="server" />
                           

                   

       

   



These code markers are very cumbersome, and I used a lot of internal comments to explain them. Please note that the arrow button that appears in the upper left corner of the header area is actually an image file from the JQuery theme I selected. Using ui-icon and ui-icon-circle-triangle-n causes the collapseArrow span to be set, causing JQuery to display An image of ico named ui-icon-circle-triangle-n. In the script area of ​​the document header, I created a function that changes the up arrow icon to a down arrow icon when we click it. Additionally, the same click event handler will show or hide the header field. div(menuDiv).

The hidden code of the Home Site page is as follows:

Code

Copy code The code is as follows:

using System;
using System .Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace HomeSite
{
///


/// Home Site (default) web page code behind class
///

public partial class _Default : System.Web.UI.Page
{
///
/// On page load we need to create the tab
/// list items for tab Interface Construction
//// & lt;/Summary & GT;
/// & LT; T;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
AddTabsToForm();
}

                 ///

/// classes. This method iterates
/// through the ArrayList building HTML controls to add to the tab panel.
///


protected void AddTabsToForm()
         {

foreach (TabDefinition tab in TabConfiguration.LoadConfiguration(this.Page))
{
HtmlGenericControl tabListItem = new HtmlGenericControl();

       tabListItem.TagName = "li";

              tabListItem.InnerHtml = " tab.DisplayName "" href="ContentLoader.aspx?ID="
tab.ID "&Path=" tab.Path
"">" tab.DisplayName "
";
panelList.Controls.Add(tabListItem);
                                              
The hidden code does not require too much explanation. The key action is to create and set the HtmlGenericControl list item, and finally it is added to the tab panel through programming.

Problems encountered

The main problem I encountered was automatically adapting to the size of the IFRAME across browsers. The solution was tested in IE 8, Firefox v3.5.6, and Google v3.0.195.38 browsers.

I have to perform browser detection and adjust the corresponding width and height based on the size of the IFRAME tested in three browsers. Chrome and FireFox appear to have a fixed height for the IFRAME when the browser changes size. However, IE8 seems to lose the padding between the IFRAME and the top of the browser. Adjusting the width and height especially for IE seems like it should minimize the "scrunching" effect of the IFRAME to the bottom of the IE window.

Restrictions

1. The following JavaScript will cause the webpage you load to jump out of the IFRAME. I don't know of any solution to this (if it exists). The Code Project website currently has code similar to the one below, making it very easy to configure the options to point to http://www.codeproject.com/, and reproduce the actions described here.


2. In the browser, the Web page is forced to change the size of the page itself, and may jump out of the IFRAME form, thereby replacing the former parent window.

3. I have not tested this solution using Safari, Opera, earlier versions of IE, or earlier versions of any other browser, so adjust the heightAdjust and widthAdjust variables appropriately in the Home Site and adapt without testing IE browser or a browser version lower than IE8.

Summary and points of interest
While this solution is not very complex, it hosts external website content through a tabbed interface. This is a feature I've seen requested by many web forums and blogs. Please note: You can also configure tags to display your own related domain names or websites (on the same server).

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template