2

Web ページ上のボタンをクリックすると、次のアクションが実行されます。つまり、スクリプトがページに挿入されます。

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

}

. . . . . .

目的のアクションを正常に実行します。しかし、ページをリロードすると、スクリプトが失われます

ボタンのクリックをトグルボタンのようにバッファリングできる方法/テクニックはありますか

Toggle.....> スクリプトが挿入されました

Toggle.....> スクリプトが分離されました

4

2 に答える 2

1

Cookieを使用して、注入したスクリプトを保存し、ページの読み込み時に再注入できます。Cookie と新しいローカル ストレージは、クライアントに状態を保存する通常の方法です。

于 2012-07-07T17:22:54.720 に答える
1

ページを離れる (そして戻る) と、javascript で発生するすべての処理がリセットされます。そのため、何かがロードされているかどうかを保存する方法が必要です。これは、これを「保存」/「記憶」する期間によって異なります。この情報を保存するためのオプションがいくつかあります - Cookie、HTML5 localStorage、HTML5 sessionStorage、および利用可能なサーバー セッションの使用 (該当する場合)。したがって、このようなものを実装したい場合は、特定のストレージが設定されているかどうかを確認するページのコード onload が必要です。その場合は、スクリプトを挿入します。これが私が意味することです:

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();" />

保管方法、保管目的、保管期間など、すべて異なることを行うため、必要な保管タイプを決定するのはあなた次第です。

于 2012-07-07T17:32:19.673 に答える