javascript – 如何强制书签只运行一次?

前端之家收集整理的这篇文章主要介绍了javascript – 如何强制书签只运行一次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的bookmarklet包含对插入到正文中的“启动器”脚本的调用.在运行时,它以类似的方式插入更多脚本(jQuery,实际应用程序)和CSS.

小书签

  1. javascript:(function(){
  2. var l = document.createElement('script');
  3. l.setAttribute('type','text/javascript');
  4. l.setAttribute('src','launcher.js');
  5. document.body.appendChild(l);
  6. })();

Launcher.js

  1. var s = document.createElement('script');
  2. s.setAttribute('type','text/javascript');
  3. s.setAttribute('src','my actual script');
  4. document.body.appendChild(s);
  5.  
  6. // I repeat a block like this once per script/css.

问题是如果单击两次书签,则会再次插入所有脚本.我该如何防止这种行为?

解决方法

您可以在窗口对象上设置一个奇怪命名的属性,因此在第一次运行时不太可能导致命名空间冲突.在后续运行中,如果属性存在,代码将不会执行:
  1. javascript:(function(){
  2. // Test for existence of your weird property
  3. if (!window.hasOwnProperty('yourWeirdPropertyX774x9ZZYy4')) {
  4.  
  5. // Run all your existing code
  6. var l = document.createElement('script');
  7. l.setAttribute('type','text/javascript');
  8. l.setAttribute('src','launcher.js');
  9. document.body.appendChild(l);
  10.  
  11. // Set the flag so this won't run again
  12. window.yourWeirdPropertyX774x9ZZYy4 = true;
  13. }
  14. })();

猜你在找的JavaScript相关文章