【问题标题】:Adding a hotkey with a Tamper Monkey script使用 Tamper Monkey 脚本添加热键
【发布时间】:2022-01-19 20:06:53
【问题描述】:

我是篡改猴子的新手,我正在尝试编写一个脚本,让我可以按下热键并让它在页面中搜索并根据搜索结果打开一个 URL。这是我到目前为止的代码:

 // ==UserScript==
// @name         Paragon to Paramount Debug Forwarding
// @namespace    http://tampermonkey.net/
// @version      1
// @description  cntrl-click forwarding from a paragon run diag to paramount debugger
// @author       taurone
// @run-at       document-start
// ==/UserScript==

function getElementByXPath(path) {
  return document.evaluate(
    path,
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
  ).singleNodeValue.nodeValue;
}

function openDebugURL(runDiag) {
  let runDiagURL = `https://my_website.com/#/debugger/${runDiag}`;
  window.open(runDiagURL);
}

function iterateThroughWorkflowTabs() {
  let workflowTabs = document.getElementsByClassName("a-tabs")[0].children;
  let tabCounter = 1;
  let runDiag;

  for (tab of workflowTabs) {
    if (tab.className.includes("active")) {
      try {
        runDiag = getElementByXPath(
          "/html/body/div[9]/div/div[2]/div/div[2]/div[2]/div/div[3]/div/div/div/pm-tab-set/div[" +
            String(tabCounter) +
            "]/pm-tab/ng-transclude/ng-transclude/pm-card/div/pm-workflow-card/div/div[2]/workflow-step-templates/div/workflow-default-step/div/div[3]/div/div[1]/div/pm-continue-button/div/aui-button/span/@data-csm-meta-pm-diagrunid"
        );
      } catch {
        runDiag = getElementByXPath(
          "/html/body/div[9]/div/div[2]/div/div[2]/div[2]/div/div[3]/div/div/div/pm-tab-set/div[" +
            String(tabCounter) +
            "]/pm-tab/ng-transclude/ng-transclude/pm-card/div/pm-workflow-card/div/div[2]/workflow-step-templates/div/workflow-default-step/div/div[3]/div/div[2]/label/@data-csm-meta-pm-diagrunid"
        );
      }
      openDebugURL(runDiag);
      return;
    }
    tabCounter++;
  }
}

function doc_keyUp(e) {
  if (e.altKey && e.key === "w") {
    unsafeWindow.iterateThroughWorkflowTabs();
  }
}

document.addEventListener("keyup", doc_keyUp, false);

在阅读 Stack Overflow 问题 adding-a-custom-keyboard-shortcut-using-userscript-to-chrome-with-tampermonkeyunsafeWindow 文档时,看起来就像在我的函数调用之前添加 unsafeWindow 一样简单,但这不起作用。我试过只是将代码插入控制台,当我这样做时它就可以工作。我不明白 Tamper Monkey 上似乎有某种设置。任何投入将不胜感激。谢谢

【问题讨论】:

    标签: javascript tampermonkey


    【解决方案1】:

    看起来 unsafeWindow 实际上是运行页面的问题。当我改变时

    function doc_keyUp(e) {
      if (e.altKey && e.key === "w") {
        unsafeWindow.iterateThroughWorkflowTabs();
      }
    }
    

    function doc_keyUp(e) {
      if (e.altKey && e.key === "w") {
        iterateThroughWorkflowTabs();
      }
    }
    

    脚本运行没有问题

    【讨论】:

    • // @grant unsafeWindow了吗?
    • 我做了一项测试,但我最终不需要它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2011-10-31
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多