我的bookmarklet包含对插入到正文中的“启动器”脚本的调用.在运行时,它以类似的方式插入更多脚本(jQuery,实际应用程序)和CSS.
小书签
javascript:(function(){ var l = document.createElement('script'); l.setAttribute('type','text/javascript'); l.setAttribute('src','launcher.js'); document.body.appendChild(l); })();
Launcher.js
var s = document.createElement('script'); s.setAttribute('type','text/javascript'); s.setAttribute('src','my actual script'); document.body.appendChild(s); // I repeat a block like this once per script/css.
问题是如果单击两次书签,则会再次插入所有脚本.我该如何防止这种行为?
解决方法
您可以在窗口对象上设置一个奇怪命名的属性,因此在第一次运行时不太可能导致命名空间冲突.在后续运行中,如果属性存在,代码将不会执行:
javascript:(function(){ // Test for existence of your weird property if (!window.hasOwnProperty('yourWeirdPropertyX774x9ZZYy4')) { // Run all your existing code var l = document.createElement('script'); l.setAttribute('type','text/javascript'); l.setAttribute('src','launcher.js'); document.body.appendChild(l); // Set the flag so this won't run again window.yourWeirdPropertyX774x9ZZYy4 = true; } })();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。