3

在油猴脚本中实现新增按钮和按钮的点击效果

 1 year ago
source link: https://www.ixiqin.com/2022/10/19/implement-new-in-a-grease-monkey-script-button-and-click-on-the-button-effect/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
text

在油猴脚本中实现新增按钮和按钮的点击效果

在油猴脚本中,有些时候,我们需要在界面当中添加一个新的按钮。这个时候我们可以使用 document.getElementById("id").innerHTML=xxx 来指定某个元素中的内容是特定的 HTML,从而实现添加一个新的按钮。

但在这个按钮上绑定事件则不是通过简单的指定 button 的 onclick 来完成的。核心原因是默认情况下,你在油猴脚本中所写的函数只运行在油猴脚本中的 Scope ,而 button 则是运行在 Document 的 Scope 下。直接绑定事件在触发时会无法找到对应的函数。

一个好的办法是为你新增的 Button 带上 ID,并通过 ID 找到对应的 Element 并添加事件绑定来实现。

参考代码如下:

// ==UserScript==
// @name         示例代码
// @namespace    https://www.ixiqin.com
// @version      0.0.1
// @description  示例代码
// @author       bestony
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';
  window.addEventListener('load', function () {
    function viewAuthor() {
      // button click event
    }

    var targetElement =document.getElementById("xxx")

    targetElement[0].innerHTML = targetElement[0].innerHTML + `  <a id="view-author">查看作者</a>`

    var link = document.getElementById("view-author");
    if (link) {
      link.addEventListener("click", viewAuthor, false);
    }
  }, false);
})();

本条目发布于2022年10月19日。属于前端分类,被贴了 开发经验油猴脚本 标签。 ← 油猴脚本不支持 Modules Javascript 导致空白脚本报错

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论 *

显示名称 *

电子邮箱地址 *

网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。

如果有人回复我的评论,请通过电子邮件通知我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK