【问题标题】:Bookmarklet to load current page without JavaScript?无需 JavaScript 即可加载当前页面的书签?
【发布时间】:2019-01-24 01:40:36
【问题描述】:

我想要一个小书签来加载当前页面/选项卡而不加载其脚本,就好像浏览器在其设置中禁用了 JavaScript。有可能吗?

它有点像这个 Chrome 扩展:https://chrome.google.com/webstore/detail/toggle-javascript/cidlcjdalomndpeagkjpnefhljffbnlo

但如果没有“切换”功能,即小书签将无法启用 JavaScript。

我喜欢这个扩展,我希望在 iOS 上有类似的东西。可以在 Safari 中禁用 JavaScript,但是每次我想加载没有脚本的页面时打开设置很烦人。

我认为书签可以让我在没有脚本的情况下快速加载当前页面,但我不知道这是否可能。随意建议其他解决方法(也许使用快捷方式/工作流程?)。

【问题讨论】:

    标签: javascript ios google-chrome mobile-safari bookmarklet


    【解决方案1】:

    一种选择是使用userscriptfetch当前页面,将响应文本解析为文档,删除文档中的所有<script>标签,然后使用window.open()打开一个新窗口,并填充它的<head><body> 与清理后的文档的<head><body>

    window.openPageWithoutScripts = async function() {
      const resp = await fetch(window.location.href);
      const text = await resp.text();
      const doc = new DOMParser().parseFromString(text, 'text/html');
      doc.querySelectorAll('script').forEach(script => script.remove());
      const w = window.open();
      w.document.head.innerHTML = doc.head.innerHTML;
      w.document.body.innerHTML = doc.body.innerHTML;
    };
    

    然后,当您想在没有任何脚本的情况下打开当前页面时,打开控制台并输入openPageWithoutScripts()

    这会去除 <script> 标记,但不会去除内联处理程序,因为内联处理程序更难预测且更难摆脱(但幸运的是,它们是不好的做法,而且通常很少见)。

    还要去除内联处理程序,创建一个包含所有可能事件的数组,然后使用这些处理程序遍历它们和 querySelectorAll 元素,然后删除该属性:

    window.openPageWithoutScripts = async function() {
      const resp = await fetch(window.location.href);
      const text = await resp.text();
      const doc = new DOMParser().parseFromString(text, 'text/html');
      doc.querySelectorAll('script').forEach(script => script.remove());
      const eventNames = ['click', 'load', 'error']; // etc
      eventNames.forEach((e) => {
        const onEventName = 'on' + e;
        document.querySelectorAll(`[${onEventName}]`).forEach((elm) => {
          elm.removeAttribute(onEventName);
        });
      });
      const w = window.open();
      w.document.head.innerHTML = doc.head.innerHTML;
      w.document.body.innerHTML = doc.body.innerHTML;
    };
    

    【讨论】:

      猜你喜欢
      • 2012-07-12
      • 1970-01-01
      • 2020-02-16
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      相关资源
      最近更新 更多