Javascript高级程序设计_7_BOM之Location&Navigator

Posted on 2018-02-26 17:02  Jonathan_C  阅读(87)  评论(0)    收藏  举报
  • Location对象,也是BOM的对象之一,很有用。它可以被window和document引用,且指的是同一个对象。
  • 通过location对象我们可以得知:与当前窗口中加载的文档有关的信息,并提供了一些导航功能
  1. location.search返回从问号到URL 末尾的所有内容,可以通过创建函数来解码返回的内容。
  2. location.assign()可以立即打开括号内的url。效果相当于window.location="..." 和location.href="..."
  3. 通过location.hash/search/hostname/pathname/port,这几种方式,修改location的属性。

    说白了,就是location记录着一个url地址,通过上述方法,可以查找,更新和修改这个地址,并同时载入新的地址。

  4. 如果用location.replace(url地址),那么当跳转到这个url之后,用户便不能通过后退回到上一个页面了。

  5. location.reload()可以重新加载页面,一般放在代码最后面

  • navigator对象
  1. 检测插件的方法。对于非IE浏览器来说,navigator对象有一个plugins的数组对象,里面存放着所有的插件名称(均为小写),所以可以这样写函数来检测某个插件是否存在
 1 function hasPlugin(checkName){
 2             checkName=checkName.toLowerCase();
 3             for(var i=0;i!=navigator.plugins.length;i++){
 4                 if(navigator.plugins[i].name.toLowerCase().indexOf(checkName)>-1){
 5                     return true;
 6                 }
 7             }
 8             return false;
 9         }
10         // alert(hasPlugin('flash'));

  2. 对于IE浏览器来说,就是另一种写法了

1         function hasIePlugin(checkName){
2             try{
3                 new ActiveXObject(checkName);
4                 return true;
5             }
6             catch(ex){
7                 return false;
8             }
9         }

  3. 所以对于所有的浏览器,可以这样写

        // A general way to detect the certain plugin
        function hasFlash(){
            var result=hasPlugin('flash');
            if(!result){
                result=hasIePlugin('ShockWaveFlash.ShockWaveFlash')
            }
            return result;
        }
        alert(hasFlash());

   缺点就是,只能逐个的检测。针对不同插件,写不同的函数。