按下按钮时动态注入脚本

Injection of scripts dynamically at button press

本文关键字:注入 脚本 动态 按钮      更新时间:2023-09-26

单击时我的网页上的按钮执行以下操作,即将脚本注入页面

function InjectToolbar() {
    var script = document.createElement('script');
    scriptFarfalla.src = 'some_Path'
    document.getElementsByTagName('head')[0].appendChild(script);
}

......

它成功地执行了所需的操作。但是当我重新加载页面时,脚本丢失了

有什么方法/技术可以缓冲按钮的点击像一个切换按钮

切换.....>注入脚本

切换.....>脚本已分离

JavaScript中发生的所有事情都会在你离开页面(并返回页面)时重置。因此,您需要一种方法来存储某些内容是否已加载。这取决于您希望将其"保存"/"记住"多长时间。您可以通过几个选项来保存此信息 - Cookie、HTML5 localStorage、HTML5 sessionStorage以及您可用的任何服务器会话使用情况(如果适用)。因此,如果你想实现这样的东西,你现在需要你的页面的代码加载来检查特定的存储,看看你是否已经设置了它。如果是这样,请注入脚本。我的意思是:

window.onload = function () {
    if (checkIfInjected()) {
        scriptInjection(true);
    }
}
function toggleInjection() {
    if (checkIfInjected()) {
        scriptInjection(false);
    } else {
        scriptInjection(true);
    }
}
function scriptInjection(inject) {
    if (inject == true) {
        var script = document.createElement('script');
        script.src = 'some_Path';
        script.id = 'injected_script_id';
        document.getElementsByTagName('head')[0].appendChild(script);
        // Set the storage to say that script is injected
    } else {
        var the_script = document.getElementById("injected_script_id");
        the_script.parentNode.removeChild(the_script);
        the_script = null;
        // Set the storage to say that script has been removed (or remove from storage altogether)
    }
}
function checkIfInjected() {
    // The following syntax is wrong for anything - you need to use the correct getter for the storage type you use
    return storage.contains("script_injected");
}
<input type="button" id="button1" onclick="toggleInjection();" />

现在由您决定所需的存储类型,因为它们都执行不同的操作,包括存储方式、存储内容以及存储时间。

您可以使用 cookie 来存储已注入的脚本,然后在页面加载时重新注入它们。Cookie 和较新的本地存储是在客户端上存储状态的常用方法。