There are more and more browsers nowadays, which makes the compatibility requirements of web design higher and higher. Commonly used ones such as setting it as the homepage and adding favorite codes are simple but the compatibility is very poor. Almost every website has a code for adding it to favorites and setting it as homepage. It doesn’t matter whether it has any effect or not. The demand should be there.
However, due to browser compatibility issues, many codes used before have lost their effect. Here is a piece of code that is compatible with various browsers. It cannot be regarded as compatible. It can only be said that it will work in unsupported browsers. Can give prompts, the code is as follows:
<!doctype html> <html> <head> <title>加入收藏和设为首页</title> <script type="text/javascript"> //加入收藏 function AddFavorite(sURL, sTitle){ sURL = encodeURI(sURL); try{ window.external.addFavorite(sURL, sTitle); } catch(e){ try{ window.sidebar.addPanel(sTitle, sURL, ""); } catch(e){ alert("加入收藏失败,请使用Ctrl+D进行添加,或手动在浏览器里进行设置."); } } } //设为首页 function SetHome(url){ if (document.all){ document.body.style.behavior='url(#default#homepage)'; document.body.setHomePage(url); } else{ alert("您好,您的浏览器不支持自动设置页面为首页功能,请您手动在浏览器里设置该页面为首页!"); } } </script> </head> <body> <a href="javascript:void(0)">设为首页</a> <a href="javascript:void(0)">加入收藏</a> </body> </html>
The above code is short and easy to understand. It is compatible with various browsers and can be added to favorites and set as homepage. If you have any questions, please feel free to ask. The editor will contact you in time. Thank you!
Let me share with you a piece of jquery code to implement the add to favorites function
//设为首页 function SetHomePage() { if (document.all) { document.body.style.behavior = 'url(#default#homepage)'; document.body.setHomePage('http://www.87cool.com'); } else if (window.sidebar) { if (window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true"); } } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage', 'http://www.87cool.com'); } } //加入收藏夹 function AddFavorite() { var title = document.title; var url = location.href; if (window.sidebar) { window.sidebar.addPanel(title, url, ""); } else if (document.all) { window.external.AddFavorite(url, title); } else { return true; } }