点击收藏制作

建议您到我的博客阅读

原贴地址https://zigao.tk/archives/10.html

前言

在浏览网页时看到了一个可以点击收藏网页的按钮
我觉得有些意思就查了查资料做了一个类似的功能

原理

各个浏览器的收藏书签方法会有差别所以要用到UA标识
IE可以直接添加书签,但是其他浏览器出于安全考虑不能用JS直接添加书签

正文

创建可以调用的JS类

首先在footer.php创建一个叫addBookmark的JS类

function addBookmark(url, title){
}

然后放上内容就成了下面这样

function addBookmark(url, title){
if (!url) {url = window.location}
    if (!title) {title = document.title}
    var browser=navigator.userAgent.toLowerCase();
    if (window.sidebar) { // Mozilla, Firefox, Netscape
        window.sidebar.addPanel(title, url,"");
    } else if( window.external) { // 这里是IE或者Chrome
        if (browser.indexOf('chrome')==-1){ // IE直接收藏
            window.external.AddFavorite( url, title);
        } else { // chrome弹出提示
            alert('请用ctrl+D收藏');
        }
    }
    else if(window.opera && window.print) { // Opera - automatically adds to sidebar if rel=sidebar in the tag
        return true;
    }
    else if (browser.indexOf('konqueror')!=-1) { // Konqueror浏览器弹出提示
        alert('请使用CTRL+B收藏本文');
    }
    else if (browser.indexOf('webkit')!=-1){ // 这里是safari浏览器
    	let url = navigator.userAgent.toLowerCase();//这一部分来自微信防封文章
        //使用toLowerCase将字符串全部转为小写 方便我们判断使用
    	if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) { // 判断是否是iOS
			alert('请手动收藏本文');//IOS移动端没有快捷键所以这样提示
		}
		if (navigator.userAgent.match(/mac/i)) { // 判断是否是Mac
			alert('请使用Command+D收藏本文');// Mac的快捷键
		}
    } else {// 其他的就这样提示
        alert('请手动收藏本文')
    }
}

最后就是这样的

<script>
function addBookmark(url, title){
if (!url) {url = window.location}
    if (!title) {title = document.title}
    var browser=navigator.userAgent.toLowerCase();
    if (window.sidebar) { // Mozilla, Firefox, Netscape
        window.sidebar.addPanel(title, url,"");
    } else if( window.external) { // IE or chrome
        if (browser.indexOf('chrome')==-1){ // ie
            window.external.AddFavorite( url, title);
        } else { // chrome
            alert('请用ctrl+D收藏');
        }
    }
    else if(window.opera && window.print) { // Opera - automatically adds to sidebar if rel=sidebar in the tag
        return true;
    }
    else if (browser.indexOf('konqueror')!=-1) { // Konqueror
        alert('请使用CTRL+B收藏本文');
    }
    else if (browser.indexOf('webkit')!=-1){ // safari
    	let url = navigator.userAgent.toLowerCase();
    	if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) { //判断是否是iOS
			alert('请手动收藏本文');
		}
		if (navigator.userAgent.match(/mac/i)) { //判断是否是Android
			alert('请使用Command+D收藏本文');
		}
    } else {
        alert('请手动收藏本文')
    }
}
</script>

注意一定要加上

调用

使用function addBookmark(url, title)调用
url是网站,title是标题
比如使用链接的方式调用

<a onclick="addBookmark('https://zigao','Zi_Gao的小站')">点击收藏</a>

后记

关于那篇自微信防封的链接https://zigao.tk/archives/7.html

发布了0 篇原创文章 · 获赞 0 · 访问量 69

猜你喜欢

转载自blog.csdn.net/weixin_44716496/article/details/104593574