1

很多这个脚本基本上是从其他人正在为他们工作的脚本中剪切和粘贴的,但是我遇到了一个奇怪的问题,.remove或者.removeChild无法运行。该脚本此时使用户脚本引擎崩溃。

// ==UserScript==
// @name     Strip Gocomics Sidebar
// @version  1
// @grant    none
// @include  https://www.gocomics.com/*
// ==/UserScript==

window.addEventListener('load', setkillsidebar);

function setkillsidebar() {
  var interval = Math.random() * 5000 + 1000;
  setTimeout(killsidebar, interval);
}

function killsidebar() {
  console.log("Start Session");
  // const adSidebar = document.querySelectorAll('.gc-container-fluid .layout-2col-sidebar, .gc-page-header--hero .layout-2col-sidebar');
  var adSidebar = document.getElementsByClassName('.gc-container-fluid .layout-2col-sidebar, .gc-page-header--hero .layout-2col-sidebar');
  console.log("Got Elements " + adSidebar.length );
  if (adSidebar) {
    console.log("Found SideBar");
    var myParent = adSidebar.parentNode;
    console.log("Made Parent");
    // myParent.remove();
    adSidebar.parentNode.removeChild(adSidebar);
    console.log("Stripped SideBar");
    var interval = Math.random() * 5000 + 1000;
    console.log("Timer Time " + interval );
    setTimeout(killsidebar, interval);
    console.log("Set Timer");
  }
}

因此,通过添加 console.log 项目,我在 Firefox 的 Web 控制台中得到以下信息:

  • 开始会话
  • 得到元素
  • 找到侧边栏
  • 成为父母

这是一个包装,我要么死.remove要么.removeChild我没有正确地做某事,或者我遇到了一个安全设置问题,它阻止我从没有人告诉我的网页中删除元素。

还有更多有趣的信息,虽然这篇文章的标题是 Greasemonkey,但 Tampermonkey 也失败了。

PS 除了一些时尚的 CSS 之外,它还被使用,它允许我在小显示器上拥有更大的漫画视图。Stylish 是否正在运行并不重要。

4

1 回答 1

1

该用户脚本存在许多问题,但它们主要归结为:您需要注意控制台中的错误消息并搜索导致它们的功能。
例如:

  • 这不是如何getElementsByClassName工作的。
  • querySelectorAll不返回节点。
  • parentNode并且removeChild都作用于单个节点。

另外:setTimeout似乎不需要第二个。并且load事件监听器也(可能)是多余的。

以下是修正了这些缺陷的脚本:

// ==UserScript==
// @name     Gocomics, Strip Sidebar
// @match    https://www.gocomics.com/*
// @version  2
// @grant    none
// ==/UserScript==

var interval = Math.random () * 5000 + 1000;
setTimeout (killsidebar, interval);

function killsidebar () {
    //-- querySelector() and querySelectorAll () are not the same.
    var adSidebar = document.querySelector ('.gc-container-fluid .layout-2col-sidebar, .gc-page-header--hero .layout-2col-sidebar');
    if (adSidebar) {
        adSidebar.parentNode.removeChild (adSidebar);
    }
}

虽然,这个脚本可能会表现得更好:

// ==UserScript==
// @name     Gocomics, Strip Sidebar
// @match    https://www.gocomics.com/*
// @version  2
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.

waitForKeyElements (
    ".gc-container-fluid .layout-2col-sidebar, .gc-page-header--hero .layout-2col-sidebar",
    removeNode
);

function removeNode (jNode) {
    jNode.remove ();
}

它使用waitForKeyElements- 比顺子更快更健壮setTimeout

于 2018-05-23T22:56:15.157 回答