浏览器脚本开发

标签: 教程 JavaScript 发布于:2020-11-16 16:42:31 编辑于:2022-11-15 12:57:00 浏览量:1585

一些例子

https://github.com/songquanpeng/browser-scripts https://greasyfork.org/en

添加 jQuery

// @require https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js

通过 window 对象使函数在页面可用

window.myFunc = funcDefinedInScript

这样在页面内调用 window.myFunc 就可以调用 funcDefinedInScript 函数。 要注意 funcDefinedInScript 内如果要调用其他函数也必须使用 window.func 的形式。

获取元素

let e = document.getElementsByClassName("class")[index];
let e = document.createElement('tag');
let e = document.getElementById('id');
let e = document.getElementsByTagName("tag")[index];

通过构建 HTML 文本来创建并插入元素

targetElement.insertAdjacentHTML('beforeend', htmlText);

  1. 'beforebegin': Before the element itself.
  2. 'afterbegin': Just inside the element, before its first child.
  3. 'beforeend': Just inside the element, after its last child.
  4. 'afterend': After the element itself.

通过 API 来创建元素

let hiddenTextArea = document.createElement('textarea');
hiddenTextArea.setAttribute("id", "hiddenTextArea");
hiddenTextArea.style.cssText = "display:hidden;";

插入元素

document.body.appendChild(e);

复制文字到剪切板

首先要创建一个隐藏的 textarea:

let hiddenTextArea = document.createElement('textarea');
hiddenTextArea.setAttribute("id", "hiddenTextArea");
hiddenTextArea.style.cssText = "display:hidden;";
document.body.appendChild(hiddenTextArea);

之后利用该 textarea 进行复制:

function copyText(text) {
    const textArea = document.getElementById('hiddenTextArea');
    textArea.textContent = text;
    document.body.append(textArea);
    textArea.select();
    document.execCommand("copy");
}

打开新的页面

window.open(https://www.google.com/search?q=${title}`);`

API 参考

https://juejin.im/post/6844903997698998285

未经允许,禁止转载,本文源站链接:https://iamazing.cn/