🙉 油猴-脚本加载前执行动作

1,548 阅读1分钟

提问: 在代码将要执行时触发该事件。

MDN中提供了element.onbeforescriptexecute

概述

当HTML文档中的<script>标签内的代码将要执行时触发该事件,如果这个script标签是用appendChild()等方法动态添加上去的,则不会触发该事件.

语法

document.onbeforescriptexecute = funcRef;

beforescriptexecute事件触发时,funcRef函数就会被调用. 传入参数eventtarget属性指向触发该事件的那个script元素.

例子

function starting(e) {
  logMessage("Starting script with ID: " + e.target.id);
}

document.addEventListener("beforescriptexecute", starting, true);
<!doctype html>
<html>
  <head>
    <title>currentScript Example</title>
    <script type="text/javascript" id="mainscript" async>

      if (document.currentScript.async) {
        console.log("Executing asynchronously");
      } else {
        console.log("Executing synchronously");
      }

      function logMessage(m) {
        var theList = document.getElementById("output");
        if (theList) {
          var newItem = document.createElement("li");
          
          newItem.innerHTML = m;
          theList.appendChild(newItem);
        }
      }
      
      function starting(e) {
        logMessage("Starting script with ID: " + e.target.id);
      }

      function finished(e) {
        logMessage("Finished script with ID: " + e.target.id);
      }
      
      document.addEventListener("beforescriptexecute", starting, true);
      document.addEventListener("afterscriptexecute", finished, true);
    </script>
  </head>
  
  <body>
    <p>Demonstration of <code>beforescriptexecute</code> and
    <code>afterscriptexecute</code>.</p>
    <h3>Output</h3>
    <ul id="output">
    </ul>
  </body>
  
  <script type="text/javascript" id="somescript">
    console.log("Look, I'm a script!");
  </script>
</html>

注意:这个方法只在Firefox上生效,Chrome上不生效。

油猴脚本替换某个js里面的内容:

// ==UserScript==
// @name        Test
// @namespace   Test
// @description TEST
// @include     *
// @version     1
// @match       http://127.0.0.1:5500/*
// @grant       GM_xmlhttpRequest
// @run-at      document-star
// ==/UserScript==

function addScript(text) {
    text = text.replace(/1/g, "2");
    var newScript = document.createElement('script');
    newScript.type = "text/javascript";
    newScript.textContent = text;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(newScript);
}

window.addEventListener('beforescriptexecute', function(e) {
    var src = e.target.src;
    if (src.search(/1\.js/) != -1) {
        e.preventDefault();
        e.stopPropagation();
        GM_xmlhttpRequest({
            method: "GET",
            url: e.target.src,
            onload: function(response) {
                addScript(response.responseText);
            }
        });
    }
});