How to save page settings for the next session? - javascript

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.

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 $.

Using localStorage is your best option, even more than a cookie.
localStorage is well supported in all browsers and most mobile devices

Related

Differentiate between page refresh and normal page load from navigating

In ASP.NET MVC C#, I used Context.Request.Headers["Referer"] to get the referrer information from which page it is navigated to. But when I refresh the page, it still shows the old referrer url.
Is there any way that I can differentiate the page refresh and page load by navigation?
JS:
$(document).ready(function () {
debugger;
var referrer = '#Context.Request.Headers["Referer"]';
}
You could use window.onbeforeload to set a cookie/sessionStorage value, the event is triggered before page refreshes or a new page is to be loaded.
// Vanilla JavaScript
window.addEventListener('onbeforeload', function() {
// your code to set value here
});
// jQuery
$(window).on('beforeunload', function() {
// your code to set value here
});
After the page is loaded (window.onload), you can check for the value. If it matches you know the page is refreshed. You must also delete it at this point.
// Vanilla JavaScript
window.onload = function() {
// your code to check value here
// remember to delete the value too
});
// jQuery
$(window).on('load', function() {
// your code to check value here
// remember to delete the value too
});
The load event fires at the end of the document loading process - all of the objects in the document are in the DOM at this point. If you want to perform the check as soon as possible you can use an IIFE:
(function refreshCheck() {
// your check here
// remember to delete the value too
})();

Javascript - keep the button disabled on all pages

I have a javascript function as below.
$("#update").click(function (){
this.disabled = true;
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
});
$("slider:changed")
Once I click on the button for updating the values, I am trying to disable the button. However, since I am using pagination, if I navigate to the second page, my button re-enables again. Is there any way to keep it disabled across all the pages?
This is the link to my work so far.
Use localStorage, or a cookie, to store the "true/false" value of the button. Check that value on every page load and assign its value back to the button's disabled property.
In your click handler, after "this.disabled = true", add:
localStorage.setItem("updateDisabled", true);
Then check for the value again on page load:
$(function () {
var disabled = localStorage.getItem("updateDisabled");
if (disabled) $('#update').attr('disabled', disabled);
});
You need to do one of two things: (1) pass the variable back to your server in some way, or (2) pass it through to the next page. You can do (1) with AJAX or a cookie, and you can do (2) with a URL parameter or a cookie. The web is "stateless," meaning (among other things) that each page doesn't know anything about what just happened on another page, unless you pass that information along somehow.

How to make Greasemonkey click automatically on a "weird" link on a specific site?

I'm not really a coder; I can hack some scripts but no more. Talk to me like a REAL NEWBIE. ;-)
I want to automatically expand two links on a page, using a GM Script.
It's a French dating site and, in the profile section, you have two places where the default is to show only partial information. So, to have all the information, you need to click on 2 additional links.
Here's a screenshot of the page with the links that I want to trigger:
(Click for larger image)
The target page is reseaucontact.com/profil/3604181
IMPORTANT: When I was testing the Script I was logged in the site... so if you click on the link & you are NOT logged-in, the site will tell you "Register to see full content" in French.
I tried to make a Script to open the first link but since the URL of the link is the SAME URL that the page (reseaucontact.com/profil/3604181) the page was just reloading in an infinite loop ;-)
Here's my First attempt to make a script the result was an infinite loop:
// ==UserScript==
// #name Reseau Contact Automatic Expander
// #version 1.0
// #author Mikha
// #include http://reseaucontact.com/profil/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
//--- Note that the contains() text is case-sensitive.
var TargetLink = $("a:contains('Voir tous les détails')")
if (TargetLink.length)
window.location.href = TargetLink[0].href
Here's the data/print-screen from Firefox Web Developer tools I have collected (When I'm logged) to find the targets/links:
The first link:
(Click for larger image)
The second link:
(Click for larger image)
I understand that when I click on the 2 links it's a GET command for "authentication request" or something like that... but I don't understand how make a script that will really "mimic" the click of my mouse to make expand the 2 sections of the profile without clicking each time.
I'm pretty sure it is simple/easy to do but after 4 hours of trying to find the information with that "kind of links" I need helps.
If you need more information or clarification just ask me.
These are AJAX-driven links with dummy values in the href. Clicking the link fires off javascript events.
The easiest thing to do in this case is to send the mouse event(s) that the javascript expects (usually, but not always a click event). See Choosing and activating the right controls on an AJAX-driven site.
Also, as a practical matter, having a GM script immediately fire on two jQuery-AJAX driven links, like those two are, might run into timing or "race" problems. For sites like this, I recommend a slight delay before clicking. Use setTimeout()Doc for the delay.
Putting it all together, the complete script could would be like:
// ==UserScript==
// #name Reseau Contact Automatic Expander
// #version 1.0
// #author Mikha
// #include http://reseaucontact.com/profil/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
//-- Delay the link clicks 333 mS and 777 mS, respectively.
setTimeout (clickLinkWithText, 333, "Voir tous les détails");
setTimeout (clickLinkWithText, 777, "Lire la suite");
function clickLinkWithText (linkText) {
var targetLink = $("a:contains('" + linkText + "')");
if (targetLink.length) {
triggerMouseEvent (targetLink[0], "click");
}
}
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
Adjust the delays if needed, and beware that there is a small chance that the site uses more, or different, events than click.
If the functionality of clicking on these truncated links is to expand the element or grab more content with an AJAX call or just show a hidden element below, then you don't probably need the link's HREF at all since its probably preventing the default behavior of following the href to a new URL.
Instead of messing with the href try triggering the click event on these links instead:
TargetLink.click();

Automatically edit url of page

At our school website, the homework pages for our teachers only shows the upcoming assignments.
To show all of the assignments you click See All and then All Homework.
The URL changes in the following way
http://example.com/apps/classes/show_class.jsp?classREC_ID=000000
http://example.com/apps/classes/show_assignment.jsp?classREC_ID=000000&showAll=true
I have looked (mainly on Stack Overflow) for solutions such as User Scripts that will automatically change the URL, but I have not been able to figure out how to do this based off of other peoples questions/answers.
To keep it short, how would I be able to modify the URL so show_class becomes show_assignment and has &showAll=true appended to it at the end.
Thanks for any help.
This would do it:
window.location = String(window.location).replace(/show_class/,"show_assignment") + "&showAll=true";
Are you trying to modify links, or modify buttons, or redirect all show_class.jsp pages?
If you are trying to modify links, buttons, etc. Edit your answer to show the appropriate HTML source of the target page.
If you want to redirect, a script like the following should do it:
// ==UserScript==
// #name _Redirect to see all homework assignments
// #include http://example.com/apps/classes/show_class.jsp?classREC_ID=*
// #run-at document-start
// ==/UserScript==
var newURL = location.href.replace (/show_class\.jsp/i, "show_assignment.jsp")
+ "&showAll=true"
;
//--- Keep browser history / back-button, uncluttered.
location.replace (newURL);

Detect first page load with jQuery?

I need to detect the first time a page loads in jQuery so that I can perform some actions only when the page loads the first time a user navigates to that page. Similar to server side code page.ispostbasck. I have tested $(document).ready and it fires every time the page loads so this will not provide what I need. I have also tried the jQuery Load function - it also fires every page load. So by page load an example is that I have an HTML input tag on the page of type button and it does not fire a postback (like an asp.net button) but it does reload the page and fires $(document).ready
Thanks
You will have to use cookie to store first load information:
if (! $.cookie("cookieName")){
// do your stuff
// set cookie now
$.cookie("cookieName", "firstSet", {"expires" : 7})
}
Note: Above example uses jQuery Cookie plugin.
An event doesn't exist that fires only when the page is loaded for the first time.
You should use jQuery's .ready() event, and then persist the fact that you've handled a first time page load using your method of choice (i.e. cookie, session variable, local storage, etc.).
Note: This method will never be fool proof unless you can store this information at the user level in a DB. Otherwise, as soon as the user clears their cookies, or whatever method you choose, the "first time loaded" code will fire again.
I just ran into this problem and this is how I handled it. Keep track of the first time the page loads by using a variable initialLoad:
var initialLoad = true;
$(document).ready(function() {
...
...
...
initialLoad = false;
});
Then in other functions, you can do this:
if (initialLoad) {
//Do work that is done when the page was first refreshed/loaded.
} else {
//Do work when it's not the initial load.
}
This works well for me. If the user is already on the page and some jQuery functions run, I now know if that user just loaded the page or if they were already on the page.
The easy solution is to use jQuery ‘Once’ plugin
$(element).once('class-name', function() {
// your javascript code
});

Categories

Resources