Reputation: 131
With my Greasemonkey script, I've added a checkbox. My idea is that if the checkbox is true do something, but if it is false do nothing.
I also want the checkbox to remember the user's last choice, so that if the user closes the webpage or browser, when he returns the checkbox is again true/false.
For example:
$('input[name=check0]').click(function(){
$('#shoutbox_b').click();
});
In this example, I want check0
to be always true. But, when I reload the page it is false until I click the checkbox again.
Upvotes: 1
Views: 1844
Reputation: 848
Using localStorage is your best option, even more than a cookie. localStorage is well supported in all browsers and most mobile devices
Upvotes: 0
Reputation: 93473
Use GM_setValue()
or localStorage
to save the input state between page loads.
Here is a complete Greasemonkey script, using jQuery, that shows the process. It is for normal, static pages. (For AJAX-driven pages you would also use waitForKeyElements
):
// ==UserScript==
// @name _Save checkbox state between page visits
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant unsafeWindow
// ==/UserScript==
//-- Get saved state:
var chk0wasChked = (localStorage.getItem ('check0_state') == "true");
//-- Get current state:
var chk0isChked = $('input[name=check0]').prop ('checked');
/*-- If the states don't match, click the checkbox to synch them up.
We need a small delay to avoid race conditions.
*/
setTimeout (setThenMonitorCheckboxState, 333);
function setThenMonitorCheckboxState () {
if (chk0wasChked != chk0isChked) {
unsafeWindow.$('input[name=check0]').click ();
}
//-- *After* the initial set, monitor & save any future state changes:
$('input[name=check0]').click ( function () {
var chk0isChked = $('input[name=check0]').prop ('checked');
localStorage.setItem ('check0_state', chk0isChked);
} );
}
Note: The question was not clear. If the original click handler for input[name=check0]
was set by the target page. Use the code as above.
But, if the original click handler for input[name=check0]
was set by the
Greasemonkey script, then change unsafeWindow.$
to just $
.
Upvotes: 2