首页 > 解决方案 > javascript 代码不能作为用户脚本工作

问题描述

我需要通过单击一个按钮来获取背景 url 代码正在运行,如您在此处看到的那样 https://jsfiddle.net/iN4sser/Lpru4hgd/3/ 但是如果我将它用作 tampermonkey 或 Violentmonkey 中的用户脚本它不起作用,结果“未定义”用户脚本

// ==UserScript==
// @name        Background Url
// @namespace   Violentmonkey Scripts
// @include       *://*jsfiddle.*/*
// @grant          GM_setValue
// @grant	       GM_xmlhttpRequest
// @grant          GM_getValue
// @grant   	   GM_addStyle
// @version     1.0
// @author      -
// @description 6/5/2020, 11:31:32 AM
// ==/UserScript==
(function() {
  window.addEventListener("load", () => {
    addButton("Get Url");
  });
var img = document.getElementsByClassName('vjs-poster'),
  style = img.currentStyle || window.getComputedStyle(img[0], false),
  bi = style.backgroundImage.slice(4, -1).replace(/"/g, '');
  function addButton(text, onclick, cssObj) {
    cssObj = cssObj || {
      position: "fixed",
      top: "15%",
      right: "4%",
      "z-index": 3,
      fontWeight: "600",
      fontSize: "14px",
      backgroundColor: "#00cccc",
      color: "white",
      border: "none",
      padding: "10px 20px"
    };
    let button = document.createElement("button"),
      btnStyle = button.style;
    document.body.appendChild(button);
    button.innerHTML = text;
    // Settin function for button when it is clicked.
    button.onclick = selectReadFn;
    Object.keys(cssObj).forEach(key => (btnStyle[key] = cssObj[key]));
    return button;
  }

  function selectReadFn() {
    var txt = document.getElementsByClassName("vjs-poster");
    // Just to show button is pressed
    alert('Image URL: ' + bi);
  }
})();

标签: javascripthtmljquerytampermonkeyuserscripts

解决方案


推荐阅读