Solved

How to keep the chekcbox state using Greasemonkey script?

Posted on 2011-02-14
30
1,465 Views
Last Modified: 2013-11-18
Hi,
I have a Greasemonkey script which adds checkboxes to each line which starts with <TR><TD.

It works fine.

Now, I want to keep the state of every single checkbox when the page is refereshed.

Here is the part of my script:
NOTE: The replacement function is called at line 33 by the function call do_modify_html_it. And this function is defined at line 162. The rest is doing some other modification. I only put the rest to give you some idea.

As I said before, I want to keep the state of these checkboxes that I placed on the page.


// ==UserScript==
// @name            aaa1
// @namespace       xxx2
// @include         http://SOMESITE
// @require         http://PATHNAME/~NAME/jquery-1.4.2.js

/*global BatCave */
BatCave = {
    log: function (str) {
        GM_log(str);
    },

    // Figures out the NAME of the cluster
    clusterNAME: function () {
        // Ignore the .dead
        var matches = window.location.search.match(/queue=([\w|\d]+)/);
        return matches ? matches[1] : null;
    },

    reloadUpperFrame: function () {
        BatCave.findFrame('top_right_frame').document.location.reload();
    },

    reloadLowerFrames: function () {
        BatCave.findFrame('middle_frame').document.location.reload();
    }
};


/*** Create checkbox for each jobID and add one more column to align the titles. Replacement is done for each <TR><TD match***/

function do_checkbox_script() {

do_modify_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]/TABLE[1]',
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/<TR><TD/gi,
    '<TR><TD style="padding-top:20px;"width: 0.1px; height: 0.1px"><form NAME="myform"><input NAME="mybox" type="checkbox"></form></TD><TD',null);
      
      

do_modifyAlignment_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]/TABLE[1]',
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/<TH>Job<\/TH>/gi,
    '<TH></TH><TH>Job</TH>',
    null);
      
}; // Ends do_checkbox_script


/*** Create Sbcheck Report link and add PassFail image for MyRuntests Report and Sbcheck Report ***/
function do_AddImage_sbcheck_script(){
       var allAnchors = window.document.evaluate(
        '//a[@href]',
        document,
        null,
        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
        null);
            
            var regTarget = /http:\/\/www-internal.(NAME)??(.)*?(devel)??(.)*?sandbox/i;
            for (i=0;i<allAnchors.snapshotLength;i++) {
                  thisAnchor = allAnchors.snapshotItem(i);
                  if (thisAnchor.href.match(regTarget)) {
                        BatCave.log("MATCHED regexp");
                        // create dynamically div tag
                        spn = document.createElement('span');
                        var spn_string = "test" + i;
                        spn.setAttribute('id',spn_string);
                        thisAnchor.parentNode.appendChild(spn);
                        BatCave.log("Set SPAN NODE");
                        BatCave.log(thisAnchor.href);
                        
                        //append an image for MyRuntest
                        var myField = document.getElementById(spn_string);
                        var oImg=document.createElement("img");
                                                
                        //retrieve the sandbox/$userNAME/ from the anchor
                        var sandboxUserNAME = thisAnchor.href.match(/sandbox\/(.*?)\//g);
                        BatCave.log(sandboxUserNAME);
                        var sbImage = 'http://www-internal/NAME/devel/' + sandboxUserNAME + 'images/PassFailMyRuntest.JPG';
                        BatCave.log(sbImage);
                        oImg.setAttribute('src', sbImage);
                        oImg.setAttribute('alt', 'Pass or Fail Image');
                        oImg.setAttribute('height', '12');
                        oImg.setAttribute('width', '12');
                        oImg.setAttribute('hspace', '5');
                        myField.appendChild(oImg);
                        BatCave.log("APPEND IMAGE");
      
                        //create sbcheck link
                        var link = document.createElement('a');
                        var sandboxUserNAMESBLocglnx = thisAnchor.href.match(/sandbox\/(.*?)glnxa64/g);
                        BatCave.log(sandboxUserNAMESBLocglnx);
                        linkTxt = document.createTextNode(">>>Sbcheck Report");
                        link.appendChild(linkTxt);
                        link.setAttribute('href','http://www-internal.NAME.com/NAME/devel/' + sandboxUserNAMESBLocglnx + '/sbcheck/report.html');
                                                
                        myField = document.getElementById(spn_string);
                        myField.appendChild(link);
                        BatCave.log("WROTE ANCHOR");
                        
                        //append an image for sbcheck
                        var myField = document.getElementById(spn_string);
                        var oImg=document.createElement("img");
                        
                        //retrieve the sandbox/$userNAME/ from the anchor
                        var sandboxUserNAME = thisAnchor.href.match(/sandbox\/(.*?)\//g);
                        BatCave.log(sandboxUserNAME);
                        var sbImage = 'http://www-internal/NAME/devel/' + sandboxUserNAME + 'images/PassFailSbcheck.JPG';
                        BatCave.log(sbImage);
                        oImg.setAttribute('src', sbImage);
                        oImg.setAttribute('alt', 'Pass or Fail Image');
                        oImg.setAttribute('height', '12');
                        oImg.setAttribute('width', '12');
                        oImg.setAttribute('hspace', '10');
                        myField.appendChild(oImg);
                        BatCave.log("APPEND IMAGE");
                  }
            }
      }; //End do_AddImage_sbcheck_script
      
/*** Overwrite the NAME attribute as MyRuntests Report for all MyRuntests links ***/
function do_NAMEAttr_script() {

do_addSbcheck_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]',
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/(<a href=.http:..www-internal.(NAME)??(.)*?(devel)??(.)*?sandbox(.*?)>)((.*?)<)/gi,
                   '$1 >>>MyRuntests Report<',
    null);

}; // Ends do_Image_script
            
window.addEventListener("load", function() { do_NAMEAttr_script() }, false);
            
window.addEventListener("load", function() { do_checkbox_script() }, false);

window.addEventListener("load", function() { do_AddImage_sbcheck_script() }, false);




function do_addSbcheck_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

function do_modify_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

function do_modifyAlignment_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

function do_addImage_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

//.user.js
0
Comment
Question by:Tolgar
  • 15
  • 15
30 Comments
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
0
 

Author Comment

by:Tolgar
Comment Utility
Thank you for your posts, but

I have previously tried to use GM_setvalue and GM_getvalue. But I couldn't make it. I would appreciate if you let me know how I can put it into this code.

The second answer refers to a solution but actually there is no solution on this page. It is the rest of the question.

Thanks,
0
 

Author Comment

by:Tolgar
Comment Utility
If the above code looks complicated, I can make the question more simple.

Once you insert multiple checkboxes on a page using Greasemonkey, how can you keep their states when you refresh the page?

I know that GM_setvalue and GM_getvalue is one way of doing it. Also, creating cookie can be another option. But I would appreciate if you could give me a working example code.

Thanks,
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
using cookies :

(function retrieved here : http://www.w3schools.com/JS/js_cookies.asp)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript">
	window.onload = function() {
		var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].name.indexOf("cb") == 0 ) {
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = state;
				}
			}
		}
	}
	
	function setCookie(c_name,value,exdays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=c_name + "=" + c_value;
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}
	
</script>
</head>
<body>
<input type="checkbox" id="cb1" name="cb1" onclick='setCookie(this.id, this.check);' /><input type="text" value="blabla" /><br />
<input type="checkbox" id="cb2" name="cb2" onclick='setCookie(this.id, this.check);' /><input type="text" value="blabla" /><br />
<input type="checkbox" id="cb3" name="cb3" onclick='setCookie(this.id, this.check);' /><input type="text" value="blabla" /><br />
</body>
</html>

Open in new window

0
 

Author Comment

by:Tolgar
Comment Utility
Thank you for your response. Do you have any idea how this can be inserted into greasemonkey. Basically, Greasemonkey script is also javascript but they way I put checkboxes does not create unique id for each checkbox. Also setcookie and getcookie functions are not on the page.

How can I implement the code you sent me using GreaseMonkey? Because the page was not created by me. I only want to modify the page using Greasemonkey script.

Thanks,
0
 

Author Comment

by:Tolgar
Comment Utility
Also, with this script, when I uncheck the box it does only keep the checked state of the box. When I refresh the page it again comes up with the checked state.

Thanks,

Artug
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
Do you know the name(s) of the checkboxes ? Do they share the same class ?

Else this should be good :


var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].name.indexOf("cb") == 0 ) {
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = state;
				}
			}
		}
	
	function setCookie(c_name,value,exdays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=c_name + "=" + c_value;
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
the important part is line 3 :
 if( inputs[i].name.indexOf("[b]cb[/b]") == 0 ) {

Open in new window


We check the name of the checkboxes. The name must start by << cb >>
But you can use class(es)
if( inputs[i].class. == "cb" ) {

Open in new window

or ids
if( inputs[i].id == "cb1" ||  inputs[i].id == "cb2" ||  inputs[i].id == "cb3"  ||  inputs[i].id == "cb4") {

Open in new window




0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
>Also, with this script, when I uncheck the box it does only keep the checked state of the box. When I refresh the page it again comes up with the checked state.

replace : onclick='setCookie(this.id, this.check);'
By : onclick='setCookie(this.id, this.checked);'
0
 

Author Comment

by:Tolgar
Comment Utility
Thank you for your response. I tried it but it still does not keep the final state. This time it all keeps it as checked. I cleared all the cookies before testing.

By the way, my main question is how to insert this cookie into greasemonkey script. Again, GM_setvalue and GM_getvalue can be better options.

Can you please give me some idea I can implement either a cookie or GM_setvalue and GM_getvalue API's to keep the final state of multiple checkboxes on a page?

(These checkboxes are created by greasemonkey script as I showed in my initial question by calling do_modify_html_it function. Tway I create it can be changed if it will solve the issue.)


Thanks in davance,


0
 

Author Comment

by:Tolgar
Comment Utility
>>Also, with this script, when I uncheck the box it does only keep the checked state of the box. When I refresh the page it again comes up with the checked state.

>replace : onclick='setCookie(this.id, this.check);'
By : onclick='setCookie(this.id, this.checked);'


This did not solve this part of the issue. I think a delete cookie function is necessary.

But my main question is how to implement this using Greasemonkey script.

Thanks,
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
The following work for me :


(function() {
		
		var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].type == "checkbox" ) {
				$(inputs[i].id).addEventListener('click', function(e) { setCookie(e.target.id); }, true);
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = (state == "1");
				}
			}
		}		
		
	function $(id) {
		return document.getElementById(id);
	}
	
	function setCookie(c_name) {
		document.cookie = c_name + "=" + ($(c_name).checked?"1":"0");
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

})();

Open in new window

0
 

Author Comment

by:Tolgar
Comment Utility
Thank you for your response. It works me as well when I put it directly on the page. However, when put this into Greasemonkey it does behave differently. I think we are getting closer to the solution.

Here is the part of the script I have in Greasemonkey. This exactly what you have given me:

function do_CheckboxCookie() {
		
		var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].type == "checkbox" ) {
				$(inputs[i].id).addEventListener('click', function(e) { setCookie(e.target.id); }, true);
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = (state == "1");
				}
			}
		}		
		
	function $(id) {
		return document.getElementById(id);
	}
	
	function setCookie(c_name) {
		document.cookie = c_name + "=" + ($(c_name).checked?"1":"0");
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

};

Open in new window



Now I call this function with load event:

window.addEventListener("load", function() { do_CheckboxCookie() }, false);

Open in new window



The behavior is a little bit different:

When I open the page all the checkboxes are not checked. This is good.

If I check a box except the very first one on the page and refresh the page then states are not kept. This is not good.

But if I check the first checkbox and refresh the page, it keeps the first checkbox as checked and make all the other checkboxes checked as well.  This is not what I want but at least I can now see that i have a cookie created.

If I uncheck the first box then all the other checkbox are unchecked as well after refreshing the checkbox. This is again an indicator of creating the cookie.

I think we are very close to the solution. It works as expected on your webpage which you have sent me regardless of the id and the checbox  name because I make all id and checkbox names same.

And this is how I call replace function in greasemonkey:

do_modify_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]/TABLE[1]', 
        document, 
        null, 
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/<TR><TD/gi,
    '<TR><TD style="padding-top:20px;"width: 0.1px; height: 0.1px"><form name="myform"><input type="checkbox" id="myboxid" name="mybox" onclick="setCookie(id="myboxid",name="mybox");"/></form></TD><TD',null);

Open in new window


And this is how I define this function in Greasemonkey:

function do_modify_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

Open in new window


I would really appreciate if you can help me to fix the last step.
0
 

Author Comment

by:Tolgar
Comment Utility
This is the entire script that i have. if you want to test on it. Just create a simple page with only the following element in  <HTML><BODY><TABLE>  tags:

<TR><TD ALIGN=CENTER >O</TD>

Open in new window



// ==UserScript==
// @name            aaa1
// @namespace       xxx2
// @include         *
/*global MyCav */
MyCav = {
    log: function (str) {
        GM_log(str);
    },

    // Figures out the name of the cluster
    clusterName: function () {
        // Ignore the .dead
        var matches = window.location.search.match(/queue=([\w|\d]+)/);
        return matches ? matches[1] : null;
    },

    reloadUpperFrame: function () {
        MyCav.findFrame('top_right_frame').document.location.reload();
    },

    reloadLowerFrames: function () {
        MyCav.findFrame('middle_frame').document.location.reload();
    }
};


/*** An interface to cookie ***/

function do_CheckboxCookie() {
		
		var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].type == "checkbox" ) {
				$(inputs[i].id).addEventListener('click', function(e) { setCookie(e.target.id); }, true);
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = (state == "1");
				}
			}
		}		
		
	function $(id) {
		return document.getElementById(id);
	}
	
	function setCookie(c_name) {
		document.cookie = c_name + "=" + ($(c_name).checked?"1":"0");
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

};
	



/*** Create checkbox for each jobID and add one more column to align the titles ***/
function do_checkbox_script() {

do_modify_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]/TABLE[1]', 
        document, 
        null, 
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/<TR><TD/gi,
    '<TR><TD style="padding-top:20px;"width: 0.1px; height: 0.1px"><form name="myform"><input type="checkbox" id="myboxid" name="mybox" onclick="setCookie(id="myboxid",name="mybox");"/></form></TD><TD',null);
	
                                                                                                                                                                          
	
do_modifyAlignment_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]/TABLE[1]', 
        document, 
        null, 
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/<TH>Job<\/TH>/gi,
    '<TH></TH><TH>Job</TH>',
    null);
	
}; // Ends do_checkbox_script


/*** Create Sbcheck Report link and add PassFail image for myruntests Report and Sbcheck Report ***/
function do_AddImage_sbcheck_script(){
	 var allAnchors = window.document.evaluate(
        '//a[@href]', 
        document, 
        null, 
        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
        null); 
		
		var regTarget = /http:\/\/www-internal.(mywork)??(.)*?(devel)??(.)*?mysandbox/i;
		for (i=0;i<allAnchors.snapshotLength;i++) {
			thisAnchor = allAnchors.snapshotItem(i);
			if (thisAnchor.href.match(regTarget)) {
				MyCav.log("MATCHED regexp");
				// create dynamically div tag
				spn = document.createElement('span'); 
				var spn_string = "test" + i;
				spn.setAttribute('id',spn_string);
				thisAnchor.parentNode.appendChild(spn);
				MyCav.log("Set SPAN NODE");
				MyCav.log(thisAnchor.href);
				
				//append an image for myruntest
				var myField = document.getElementById(spn_string);
				var oImg=document.createElement("img");
								
				//retrieve the mysandbox/$username/ from the anchor 
				var mysandboxUserName = thisAnchor.href.match(/mysandbox\/(.*?)\//g);
				MyCav.log(mysandboxUserName);
				var sbImage = 'http://www-internal/mywork/devel/' + mysandboxUserName + 'images/PassFailmyruntest.JPG';
				MyCav.log(sbImage);
				oImg.setAttribute('src', sbImage);
				oImg.setAttribute('alt', 'Pass or Fail Image');
				oImg.setAttribute('height', '12');
				oImg.setAttribute('width', '12');
				oImg.setAttribute('hspace', '5');
				myField.appendChild(oImg);
				MyCav.log("APPEND IMAGE");
	
				//create mycheck link
				var link = document.createElement('a');
				// match all the path upto the end of last directory. This is the directory where sbcheck locates.
				// e.g. http://www-internal/mywork/devel/mysandbox/byu/mytw_bug_myruntests/glnxa64_g68/mybugs/myge/mychecks.html  
				// and the match will be http://www-internal/mywork/devel/mysandbox/byu/mytw_bug_myruntests/glnxa64_g684598/mybugs/mygecks/
				var mysandboxUsernameSBLocglnx = thisAnchor.href.match(/mysandbox\/(.*?)[^\/]+$/g);
				MyCav.log(mysandboxUsernameSBLocglnx);
				linkTxt = document.createTextNode(">>>myCheck Report");
				link.appendChild(linkTxt);
				link.setAttribute('href','http://www-internal.mywork.com/mywork/devel/' + mysandboxUsernameSBLocglnx + '/myCheck/report.html');
								
				myField = document.getElementById(spn_string);
				myField.appendChild(link);
				MyCav.log("WROTE ANCHOR");
				
				//append an image for myCheck
				var myField = document.getElementById(spn_string);
				var oImg=document.createElement("img");
				
				//retrieve the mysandbox/$username/ from the anchor 
				var mysandboxUserName = thisAnchor.href.match(/mysandbox\/(.*?)\//g);
				MyCav.log(mysandboxUserName);
				var sbImage = 'http://www-internal/mywork/devel/' + mysandboxUserName + 'images/PassFailmyCheck.JPG';
				MyCav.log(sbImage);
				oImg.setAttribute('src', sbImage);
				oImg.setAttribute('alt', 'Pass or Fail Image');
				oImg.setAttribute('height', '12');
				oImg.setAttribute('width', '12');
				oImg.setAttribute('hspace', '10');
				myField.appendChild(oImg);
				MyCav.log("APPEND IMAGE");
			}
		}
	}; //End do_AddImage_myCheck_script
	
/*** Overwrite the name attribute as myruntests Report for all myruntests links ***/
function do_nameAttr_script() {

do_addmyCheck_html_it(
    window.document,
    document.evaluate(
        '/HTML[1]/BODY[1]', 
        document, 
        null, 
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null).singleNodeValue,/(<a href=.http:..www-internal.(mywork)??(.)*?(devel)??(.)*?mysandbox(.*?)>)((.*?)<)/gi,
                   '$1 >>>myruntests Report<',
    null);

}; // Ends do_Image_script
		
window.addEventListener("load", function() { do_nameAttr_script() }, false);
		
window.addEventListener("load", function() { do_checkbox_script() }, false);

window.addEventListener("load", function() { do_AddImage_myCheck_script() }, false);

window.addEventListener("load", function() { do_CheckboxCookie() }, false);




function do_addmyCheck_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

function do_modify_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

function do_modifyAlignment_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

function do_addImage_html_it(doc, element, match_re, replace_string) {
    match_re = new RegExp(match_re);
    if (element.innerHTML) {
element.innerHTML = element.innerHTML.replace(match_re, replace_string);
    };
};

//.user.js

Open in new window

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 82

Expert Comment

by:leakim971
Comment Utility
With this simple page :

(replace the extension txt -> js)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="alert('page reloaded!')">
<input type="checkbox" id="cb1" name="cb1" /><input type="text" value="blabla" /><br />
<input type="checkbox" id="cb2" name="cb2" /><input type="text" value="blabla" /><br />
<input type="checkbox" id="cb3" name="cb3" /><input type="text" value="blabla" /><br />
</body>
</html>

Open in new window

checkboxStatus.user.txt
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
The latest code was tested with GM
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
0
 

Author Comment

by:Tolgar
Comment Utility
Thank you for your response. I agree that this solution works when the checkbox is already on the page as in your example. However, if the checkbox is created by Greasemonkey as in my case, it does not work as expected.

Can you please test it as I did it by creating the checkbox using Greasemonkey?

Thanks,
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
I understand now the problem, let me do some tests...
0
 

Author Comment

by:Tolgar
Comment Utility
Thanks,

I really appreciate for your effort. Please let me know if there is a way of increasing points of this question above 500. It really deserves more.

0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
You're welcome! Thanks you! Check this :


(function() {
		
		document.addEventListener('click', function(e) { if(e.target.type == "checkbox") setCookie(e.target.id); }, true);
		var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].type == "checkbox" ) {
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = (state == "1");
				}
			}
		}		

	function $(id) {
		return document.getElementById(id);
	}
	
	function setCookie(c_name) {
		var c = c_name + "=" + ($(c_name).checked?"1":"0");
		document.cookie = c;
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

})();

Open in new window

0
 

Author Comment

by:Tolgar
Comment Utility
Well, I tried it but it did not work as expected. Let me tell you how I added to Greasemonkey. Maybe there is problem is that part. Let me tell you how I added the code to my GM script:

function doKeepCheckboxStatus() {
		
		document.addEventListener('click', function(e) { if(e.target.type == "checkbox") setCookie(e.target.id); }, true);
		var inputs = document.getElementsByTagName("input");
		for(var i=0;i<inputs.length;i++) {
			if( inputs[i].type == "checkbox" ) {
				var state = getCookie( inputs[i].id )
				if( state != null ) {
					inputs[i].checked = (state == "1");
				}
			}
		}		

	function $(id) {
		return document.getElementById(id);
	}
	
	function setCookie(c_name) {
		var c = c_name + "=" + ($(c_name).checked?"1":"0");
		document.cookie = c;
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

};

Open in new window


Then I call this doKeepCheckboxStatus function as below:

window.addEventListener("load", function() { doKeepCheckboxStatus() }, false);

Open in new window


Am I doing something wrong. When I look at the cookies under Firefox, I can see my cookie that is created. But the checkbox status is not kept.

Thanks,
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
we set & save checkboxes status with their id. we set back their state when the page is fully loaded so if the checkboxes are not created we can't set back their state. We need to do this job after added the checkboxes. I will take a look to your code to see where you're creating them.
0
 

Author Comment

by:Tolgar
Comment Utility
The checkbox is created by calling do_modify_html_it function in the code I have sent you.

Thanks,
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
Comment Utility
>because I make all id and checkbox names same

id must be unique in a document. So we need to generate a unique id each time we add a checkbox, check this new GM script :
(function() {
	
	counter = 0;
	document.addEventListener('click', function(e) { if(e.target.type == "checkbox") { setCookie(e.target.id); } }, true);
	
	var _doc = window.document;
	var _element = document.evaluate('/HTML[1]/BODY[1]/TABLE[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
	var _regexp = /<TR><TD/gi
	var _repstr = '<TR><TD style="padding-top:20px;"width: 0.1px; height: 0.1px"><form name="myform"><input type="checkbox" id="mybox_X" name="mybox" /></form></TD><TD';		
	do_modify_html_it(_doc, _element, _regexp, _repstr);
	
	do_restore_checkboxState("mybox");
	
	function do_restore_checkboxState(checkboxName) {
		var checkboxes = document.getElementsByName(checkboxName);
		for(var i=0;i<checkboxes.length;i++) {
			var state = getCookie( checkboxes[i].id )
			if( state != null ) {
				checkboxes[i].checked = (state == "1");
			}
		}
	}

	function do_modify_html_it(doc, element, match_re, replace_string) {
		match_re = new RegExp(match_re);
		if(element.innerHTML) {
			element.innerHTML = element.innerHTML.replace(match_re, function($1) { counter++; return replace_string.replace("mybox_X", "mybox"+counter) });
		}
	}

	function setCookie(c_name) {
		var c = c_name + "=" + (document.getElementById(c_name).checked?"1":"0");
		document.cookie = c;
	}

	function getCookie(c_name) {
		var i,x,y,ARRcookies=document.cookie.split(";");
		for (i=0;i<ARRcookies.length;i++) {
			x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
			y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
			x=x.replace(/^\s+|\s+$/g,"");
			if (x==c_name) {
				return unescape(y);
			}
		}
	}

})();

Open in new window

0
 

Author Comment

by:Tolgar
Comment Utility
Awesome!!!

It works as expected.

Thank you for your great effort!!

0
 

Author Closing Comment

by:Tolgar
Comment Utility
Great job!!
This solution and the question requires more than 500 points. Let me know if there is a way to make it over 500.

Thanks,
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
No problem for the points, thank you! Have a nice week-end!
0
 

Author Comment

by:Tolgar
Comment Utility
Hi,
I have an extension question to this previous question. Now, everthing works fine but there is a  small bug. Since we assign the IDs using a counter, when I open up another page in the same domain by clicking the Job ID on the main page, it brings me a page where I create some other chekcboxes. Then I select to the previous page and the checkboxes which I haven't checke yet are also selected, because the last page that I navigated to created the ID using the counter. So there should be something more unique.

I tried to use the Job ID instead of the counter, because they are absolutely unique. So at this point I need to extract the Job Id. Here is the part of my code which I have changed from the last one you sent me. In function "do_replace_html_it" I replaced "counter" with a function call to getJobNumber(). The rest is same.

	
	function do_replace_html_it(doc, element, match_re, replace_string) {
		match_re = new RegExp(match_re);
		if(element.innerHTML) {
			element.innerHTML = element.innerHTML.replace(match_re, function($1) { return replace_string.replace("mybox_X", "mybox"+getJobNumber()) });
		}
	}

	// This function is for the single job page 
	function do_replace_html_itJob(doc, element, match_re, replace_string) {
		match_re = new RegExp(match_re);
		if(element.innerHTML) {
			element.innerHTML = element.innerHTML.replace(match_re, function($1) { counterJob++; return replace_string.replace("myJobbox_X", "myJobbox"+counterJob) });
		}
	}
	
	function getJobNumber(){
		var n = 0;
		var allAnchors = window.document.evaluate(
			'//a[@href]', 
			document, 
			null, 
			XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
			null); 
	
	        var regTarget = /cgi-bin\/jobtree\.cgi\?queue=/i;			
			thisAnchor = allAnchors.snapshotItem(n);
			n = n + 1;
			if (thisAnchor.href.match(regTarget)) {
				var JobId = thisAnchor.href.match(/(?:job=)(\d+)/g);
			}
	return JobId;
	};

Open in new window


Now It does not work as I expected.
The jobId is a unique number in everyline where I have a checkbox like this:

<A HREF='/cgi-bin/jobtree.cgi?queue=C&job=123456' TARGET=middle_frame

Open in new window


In here 123456 is the ID which I want to use instead of the counter. I am attaching a sample snapshot.


Do you have any idea?

Please let me know if I need to create another question but then it can be more complicated to explain everything from the beginning.


Thanks,
2-lines.bmp
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now