How to copy without user click - javascript

Im using tampermonkey to make a script in js to copy and password and open the site for that password so i can easily paste it in. However, I am having some trouble with the copying part. from what i see there is a need user interaction to copy something and i understand this is for security purposes and people dont want random things going into their clipboard. Is there a way to turn this off in my browser (Chrome). If not i have one more idea. I use a key combo (CTRL DOWN ARROW) to activate the script to copy and open a new tab and i use that user interaction to copy the text.
This is what i have so far
(function() {
'use strict';
function KeyPress(e) {
var evtobj = window.event ? event : e
if (evtobj.keyCode == 40 && evtobj.ctrlKey) {
var aTags = document.getElementsByTagName("td");
var searchText = "WP-Admin Password";
//Finding The Password
var pass;
var found1;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].textContent == searchText) {
//found 1 is the element that has the search phrase
found1 = aTags[i];
//This is where im trying to copy to my clipboard the text content.
found1.nextSibling.firstChild.textContent; //wp Admin Password
;
break;
}
}
//Finding a Dev url if they have one
var pass3;
var found3;
var dev;
for (var k = 0; k < aTags.length; k++) {
if (aTags[k].textContent == "Development URL") {
found3 = aTags[k];
if (found3.nextSibling.firstChild.firstChild !== "") {
found3.nextSibling.firstChild.firstChild.click();
} else {
dev = false;
}
break;
}
}
//fining the live url and going to it
var pass2;
var found2;
if (!dev) {
for (var j = 0; j < aTags.length; j++) {
if (aTags[j].textContent == "Website") {
found2 = aTags[j];
found2.nextSibling.firstChild.firstChild.click();; //url
break;
}
}
}
}
}
document.onkeydown = KeyPress;
})();

Try GM_setClipboard
Detail at: https://github.com/scriptish/scriptish/wiki/GM_setClipboard
// ==UserScript==
// #name _YOUR_SCRIPT_NAME
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #grant GM_setClipboard
// ==/UserScript==
GM_setClipboard ("The clipboard now contains this sentence.");

Alright I figured out a solution
This solution ONLY works if you are using tamper monkey or grease monkey
you can add
// #grant GM_setClipboard
To your script and it will allow you to use the Gm_setclipboard() func. to copy things to clipboard.

Related

GM_xmlhttpRequest data is being placed in the wrong places

I am using the following excellent userscript (for Chrome, Chrome's Tampermonkey and Firefox Greasemonkey). It's supposed to display movie ratings next to each IMDb movie link, but it stopped working properly.
This is the complete script:
// ==UserScript==
// #name Add IMDb rating next to all IMDb links (+voter count)
// #author Ali
// #description Adds movie ratings and number of voters to any IMDb link. Modified version of http://userscripts.org/scripts/show/9174
// #include *
// #version 2013-05-12
// #namespace http://userscripts.org/scripts/show/96884
// #grant GM_xmlhttpRequest
// #downloadURL http://www.alibakir.com/upload/addimdbratings.js
// #updateURL http://www.alibakir.com/upload/addimdbratings.js
// ==/UserScript==
var IMDBpluginlinks = document.links;
var IMDBcontinueelement=document.createElement("button");
IMDBcontinueelement.innerHTML="Get rating";
function processIMDBLinks(s){
IMDBcontinueelement.style.display = 'none';
var r=0;
for (IMDBi = s; IMDBi < IMDBpluginlinks.length; IMDBi++) {
if (IMDBpluginlinks[IMDBi].href.indexOf("/title/") != -1 && IMDBpluginlinks[IMDBi].href.indexOf("imdb.") != -1){
if(r>300){
IMDBcontinueelement.onclick=function(){ processIMDBLinks(IMDBi); };
IMDBcontinueelement.style.display='inline';
IMDBpluginlinks[IMDBi].parentNode.insertBefore(IMDBcontinueelement, IMDBpluginlinks[IMDBi]);
break;
}
r++;
GM_xmlhttpRequest({
method: 'get',
headers: {
},
url: IMDBpluginlinks[IMDBi].href,
onload: function (IMDBi){return function(result) {
rating = result.responseText.match(/Users rated this (.*) \(/);
votes = result.responseText.match(/\((.*) votes\) -/);
IMDBpluginlinks[IMDBi].parentNode.insertBefore(document.createElement("span"), IMDBpluginlinks[IMDBi]).innerHTML = (rating ? "<b> [" + rating[1] + " - "+votes[1]+"] </b>" : "<b style='color: red;'>[NA] </b> ");
}}(IMDBi)
});
}
}
}
processIMDBLinks(0);
And this is how an example page looks at the moment:
As you can see, the script displays the results in the wrong places.
Why does it present them in the wrong place and how can it be fixed?
The issue causing your main complaint (results in the wrong places) is that GM_xmlhttpRequest operates asynchronously (which is good) and the onload was improperly constructed.
You either need to wrap the call to GM_xmlhttpRequest in a proper closure or provide a context in the GM_xmlhttpRequest call. (See the code below.)
For more information on why closures are needed, see this answer to the same type of problem.
Other big problems include AJAX-fetching dozens of improper links and firing on every page and iframe. Both of these slow the browser down quite a bit.
Don't use #include *. Even if you don't mind, other users of the script will. Add #include or #match lines for just the sites that you know have IMDB links.
I thought that I might want to use this script myself, so I started cleaning it up. You can read the inline comments and compare to the original script for an idea of some of the lesser problems. (Don't use onclick and always check match returns, etc.)
// ==UserScript==
// #name add IMDb rating next to all IMDb links (+voter count)
// #description Adds movie ratings and number of voters to any imdb link. Modified version of http://userscripts.org/scripts/show/96884
// #match *://www.imdb.com/*
// #grant GM_xmlhttpRequest
// ==/UserScript==
var maxLinksAtATime = 50; //-- pages can have 100's of links to fetch. Don't spam server or browser.
var fetchedLinkCnt = 0;
function processIMDB_Links () {
//--- Get only links that could be to IMBD movie/TV pages.
var linksToIMBD_Shows = document.querySelectorAll ("a[href*='/title/']");
for (var J = 0, L = linksToIMBD_Shows.length; J < L; J++) {
var currentLink = linksToIMBD_Shows[J];
/*--- Strict tests for the correct IMDB link to keep from spamming the page
with erroneous results.
*/
if ( ! /^(?:www\.)?IMDB\.com$/i.test (currentLink.hostname)
|| ! /^\/title\/tt\d+\/?$/i.test (currentLink.pathname)
)
continue;
if (! currentLink.getAttribute ("data-gm-fetched") ){
if (fetchedLinkCnt >= maxLinksAtATime){
//--- Position the "continue" button.
continueBttn.style.display = 'inline';
currentLink.parentNode.insertBefore (continueBttn, currentLink);
break;
}
fetchTargetLink (currentLink); //-- AJAX-in the ratings for a given link.
//---Mark the link with a data attribute, so we know it's been fetched.
currentLink.setAttribute ("data-gm-fetched", "true");
fetchedLinkCnt++;
}
}
}
function fetchTargetLink (linkNode) {
//--- This function provides a closure so that the callbacks can work correctly.
/*--- Must either call AJAX in a closure or pass a context.
But Tampermonkey does not implement context correctly!
(Tries to JSON serialize a DOM node.)
*/
GM_xmlhttpRequest ( {
method: 'get',
url: linkNode.href,
//context: linkNode,
onload: function (response) {
prependIMDB_Rating (response, linkNode);
},
onload: function (response) {
prependIMDB_Rating (response, linkNode);
},
onabort: function (response) {
prependIMDB_Rating (response, linkNode);
}
} );
}
function prependIMDB_Rating (resp, targetLink) {
var isError = true;
var ratingTxt = "** Unknown Error!";
if (resp.status != 200 && resp.status != 304) {
ratingTxt = '** ' + resp.status + ' Error!';
}
else {
if (/\(awaiting \d+ votes\)|\(voting begins after release\)|in development/i.test (resp.responseText) ) {
ratingTxt = "NR";
isError = false;
}
else {
var ratingM = resp.responseText.match (/Users rated this (.*) \(/);
var votesM = resp.responseText.match (/\((.*) votes\) -/);
if (ratingM && ratingM.length > 1 && votesM && votesM.length > 1) {
isError = false;
ratingTxt = ratingM[1] + " - " + votesM[1];
}
}
}
var resltSpan = document.createElement ("span");
resltSpan.innerHTML = '<b> [' + ratingTxt + '] </b> ';
if (isError)
resltSpan.style.color = 'red';
//var targetLink = resp.context;
//console.log ("targetLink: ", targetLink);
targetLink.parentNode.insertBefore (resltSpan, targetLink);
}
//--- Create the continue button
var continueBttn = document.createElement ("button");
continueBttn.innerHTML = "Get ratings";
continueBttn.addEventListener ("click", function (){
fetchedLinkCnt = 0;
continueBttn.style.display = 'none';
processIMDB_Links ();
},
false
);
processIMDB_Links ();

Stopping content script in chrome extension

I have developed chrome extension , I have added ,
chrome.browserAction.onClicked.addListener
which will start the script once clicked on , the script in turn will add a div at the bottom of the web page on the tab the browser action is clicked ,
All I have to do is , I need to add a close link which will stop the content script and close the div at the bottom ,
I have tried windows.close() , self.close() but nothing seems to work ,I would atleast want it to work in a way that 2nd time some one clicks on browser action, the script should stop.
Here is my code,
background.js
chrome.browserAction.onClicked.addListener( function() {
chrome.tabs.executeScript( { file: 'myscript.js' } );
});
myscript.js
document.body.appendChild(div);
document.addEventListener("click",
function (e) {
e.preventDefault();
var check = e.target.getAttribute("id");
var check_class = e.target.getAttribute("class");
if(check=="ospy_" || check=="ospy_id" || check=="ospy_text" || check=="ospy_el" || check=="ospy_class" || check=="ospy_name" || check=="ospy_href" || check=="ospy_src"|| check=="ospy_wrapper"|| check=="ospy_style"|| check=="ospy_rx"|| check=="ospy_con"|| check_class=="ospy_td"|| check=="ospy_main_tab"|| check_class=="ospy_tab" || check_class=="ospy_ip"|| check_class=="ospy_lab")
{
}
else{
document.getElementById('ospy_id').value = "";
document.getElementById('ospy_class').value = "";
document.getElementById('ospy_el').value = "";
document.getElementById('ospy_name').value = "";
document.getElementById('ospy_style').value = "";
document.getElementById('ospy_href').value = "";
document.getElementById('ospy_text').value = "";
document.getElementById('ospy_src').value = "";
document.getElementById('ospy_con').value = "";
document.getElementById('ospy_').value = "";
document.getElementById('ospy_rx').value = "";
var dom_id=e.target.getAttribute("id");
// var dom_id = e.target.id.toString();
var dom_name = e.target.name.toString();
var dom_class = e.target.className.toString();
// var dom_class = this.class;
var dom_html = e.target.innerHTML;
var dom_href = e.target.getAttribute("href");
var dom_text = e.target.text;
var dom_el= e.target.tagName;
var dom_src= e.target.src;
//var XPATH = e.target.innerHTML;
var rel_xpath = "";
var field ="";
var field_value = "";
field="id";
field_value = dom_id;
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
if(dom_id == null){
field="href";
field_value= dom_href;
//var rel_xpath = dom_el+"[contains(text(), '"+dom_text+"')]";
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
if(dom_href==null || dom_href=="#")
{
field="src";
field_value= dom_src;
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
//rel_xpath = "nope nothing";
if(dom_src==null)
{
var rel_xpath = dom_el+"[contains(text(), '"+dom_text+"')]";
if(dom_text=="")
{
field="class";
field_value= dom_class;
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
}
}
}
}
var con_xpath = "";
var con_xpath = dom_el+"[contains(text(), '"+dom_text+"')]";
if(dom_text==null)
{
con_xpath = "NA";
}
var css ="color: ";
css += getComputedStyle(e.target).color;
css +="\nWidth: ";
css += getComputedStyle(e.target).width;
css +="\nHeight: ";
css += getComputedStyle(e.target).height;
css +="\nbg: ";
css += getComputedStyle(e.target).background;
css +="\nfont: ";
css += getComputedStyle(e.target).font;
css +="\nvertical-align: ";
css += getComputedStyle(e.target).verticalalign;
css +="\nmargin: ";
css += getComputedStyle(e.target).margin;
var node = getXPath(e.target.parentNode);
document.getElementById('ospy_id').value = dom_id;
document.getElementById('ospy_class').value = dom_class;
document.getElementById('ospy_el').value = dom_el;
document.getElementById('ospy_name').value = dom_name;
document.getElementById('ospy_style').value = css;
document.getElementById('ospy_href').value = dom_href;
document.getElementById('ospy_text').value = dom_text;
document.getElementById('ospy_src').value = dom_src;
document.getElementById('ospy_').value = node;
document.getElementById('ospy_rx').value =rel_xpath;
document.getElementById('ospy_con').value =con_xpath;
}},
false);
window.close() is for closing a window, so no wonder it does not work.
"Unloading" a content-script is not possible, but if you want to remove an element (e.g. your div) from the DOM, just do:
elem.parentNode.removeChild(elem);
(Whether you bind this behaviour to a link/button in your <div> or have the browser-action, trigger an event in the background-page that sends a message to the corresponding content-script which in turn removes the element is up to you. (But clearly the former is much more straight-forward and efficient.)
If you, also, want your script to stop performing some other operation (e.g. handling click events) you could (among other things) set a flag variable to false (when removing the <div>) and then check that flag before proceeding with the operation (e.g. handling the event):
var enabled = true;
document.addEventListener('click', function (evt) {
if (!enabled) {
/* Do nothing */
return;
}
/* I am 'enabled' - I'll handle this one */
evt.preventDefault();
...
/* In order to "disable" the content-script: */
div.parentNode.removeChild(div);
enabled = false;
Notes:
If you plan on re-enabling the content-script upon browser-action button click, it is advisable to implement a little mechanism, where the background-page sends a message to the content-script asking it to re-enable itself. If the content-script is indeed injected but disabled, it should respond back (to confirm it got the message) and re-enable itself. If there is no response (meaning this is the first time the user clicks the button on this page, the background-page injects the content script.
If it is likely for the content script to be enabled-disabled multiple times in a web-pages life-cycle, it would be more efficient to "hide" the <div> instead of removing it (e.g.: div.style.display = 'none';).
If you only need to disable event handler, instead of using the enabled flag, it is probably more efficient to keep a reference to the listener you want to disable and call removeEventListener().
E.g.:
function clickListener(evt) {
evt.preventDefault();
...
}
document.addEventListener('click', clickListener);
/* In order to "disable" the content-script: */
div.parentNode.removeChild(div);
document.removeEventListener('click', clickListener);

Greasemonkey script to hide stackoverflow posts?

I found myself reading the same questions over and over, so I wanted a way to hide questions.
I have a script to does what is suppose to do, however it cripples existing javascript, such as the upvote button and adding tags when asking questions. Does anyone know why this is happening, or how to fix it?
Edit: oh, in the error console I am getting:
Error: $ is not a function
Source File: http://cdn.sstatic.net/js/stub.js?v=b7084478a9a4
Line: 1
Edit2:
The solution
(fixed #17/06/2014)
// ==UserScript==
// #name StackOverflowHidePosts
// #namespace StackOverflowHidePosts
// #description Allows you to hide questions on Stack Overflow.
// #include http://stackoverflow.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
var idListString = GM_getValue('idList', '');
var idList = idListString.split(',');
GM_setValue('idList', idList.join(','));
function getId (idString)
{
return idString.split('-')[2];
}
function removeQuestion (e)
{
var id = getId(e.data.questionSummaryDiv.id);
$(e.data.questionSummaryDiv).hide(250);
idList.push(id);
setTimeout(function() {
GM_setValue('idList', idList.join(','));
}, 0);
return false;
}
$('div.question-summary').each(function (index, questionSummaryDiv)
{
var id = getId(questionSummaryDiv.id);
if (idList.indexOf(id) != -1)
{
$(questionSummaryDiv).hide();
return;
}
var link = $('<a><em>(Hide Post)</em></a>');
link.attr('href', '#' + questionSummaryDiv.id);
link.click({questionSummaryDiv: questionSummaryDiv}, removeQuestion);
$('div.started', questionSummaryDiv).append(link);
});
Never inject JS if you don't have to, and never use the page's jQuery in FF GM -- that's the main source of errors in this case.
The entire script should be:
// ==UserScript==
// #name StackOverflowImTooStupidMarker
// #namespace StackOverflowImTooStupidMarker
// #description Allows you to hide questions on Stack Overflow when you can't answer them.
// #include http://stackoverflow.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
var idListString = GM_getValue('idList', '');
var idList = idListString.split(',');
GM_setValue('idList', idList.join(','));
function getId (idString)
{
return idString.split('-')[2];
}
function removeQuestion (e)
{
var id = getId(e.data.questionSummaryDiv.id);
$(e.data.questionSummaryDiv).hide(250);
idList.push(id);
setTimeout(function() {
GM_setValue('idList', idList.join(','));
}, 0);
return false;
}
$('div.question-summary').each(function (index, questionSummaryDiv)
{
var id = getId(questionSummaryDiv.id);
if (idList.indexOf(id) != -1)
{
$(questionSummaryDiv).hide();
return;
}
var link = $('<a><em>(Too Stupid)</em></a>');
link.attr('href', '#' + questionSummaryDiv.id);
link.click({questionSummaryDiv: questionSummaryDiv}, removeQuestion);
$('div.started', questionSummaryDiv).append(link);
});
That script attempts to include jQuery first thing:
(function()
{
if (typeof unsafeWindow.jQuery == 'undefined')
{
var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement, GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
GM_JQ.type = 'text/javascript';
GM_JQ.async = true;
GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
}
GM_wait();
})();
This issue there is that jQuery is guaranteed to be loaded on Stack Overflow to begin with...if it's not present you have much bigger issues. That whole jQuery replacement shouldn't happen, as it's both impacting already registered plugins (nuking then) and using a newer version of jQuery that Stack Exchange currently does, meaning other potentially breaking changes as well.
Since the script needs none of the latest functionality, that entire chunk above should simply be:
GM_wait();
For the other issues, there are a few more $ conflicts...but you still want to be safe with respect to load order here. Here's a cheaper and still safe version that...well, works:
var idListString = GM_getValue('idList', '');
var idList = idListString.split(',');
GM_setValue('idList', idList.join(','));
GM_wait();
function GM_wait() {
if (typeof unsafeWindow.jQuery == 'undefined') {
window.setTimeout(GM_wait, 100);
return;
}
unsafeWindow.jQuery(function($) {
var link = $('<em>(Too Stupid)</em>').click(removeQuestion);
$('div.question-summary').each(function (index, questionSummaryDiv) {
var id = getId(questionSummaryDiv.id);
if (idList.indexOf(id) != -1) {
$(questionSummaryDiv).hide();
} else {
$('div.started', questionSummaryDiv).append(link.clone(true));
}
});
});
}
function getId (idString) {
return idString.split('-')[2];
}
function removeQuestion () {
var q = unsafeWindow.jQuery(this).closest("div.question-summary").hide(250);
idList.push(getId(q.attr("id")));
setTimeout(function() {
GM_setValue('idList', idList.join(','));
}, 0);
return false;
}

Works as javascript, but doesn't work as a Greasemonkey script?

I'm making a Greasemonkey script to add download links beside videos on cnn.com.
I used a saved version of the HTML page to test my script and was able to get it to work perfectly. Then when I put the javascript into Greasemonkey and tried it on the actual site, it didn't work.
This is the not the full script, but the part of the script with the problem. It is simply supposed to add a link at the bottom of every div with the "sec_video_box" class (as seen in the picture).
// ==UserScript==
// #name CNN Download
// #namespace Cool
// #description CNN Download
// #include http://*cnn.com/video/*
// ==/UserScript==
var getClass = function(clssName, rootNode /*optional*/){
var root = rootNode || document,
clssEls = [],
elems,
clssReg = new RegExp("\\b"+clssName+"\\b");
// use the built in getElementsByClassName if available
if (document.getElementsByClassName){
return root.getElementsByClassName(clssName);
}
// otherwise loop through all(*) nodes and add matches to clssEls
elems = root.getElementsByTagName('*');
for (var i = 0, len = elems.length; i < len; i+=1){
if (clssReg.test(elems[i].className)) clssEls.push(elems[i])
}
return clssEls;
};
function insertlinks() {
var boxes = getClass("sec_video_box");
for (i=0; i<boxes.length; i++) {
var theboxid = boxes[i].getAttribute("id");
document.getElementById(theboxid).innerHTML = document.getElementById(theboxid).innerHTML + 'link';
}
}
window.onload = insertlinks ();
Can someone tell me what I'm doing wrong?
The 3 biggest problems with that script are:
You can't use window.onload that way; see GM Pitfall #2: Event Handlers.   Always use addEventListener() or jQuery.
Those video objects are AJAXed-in after the document loads, anyway.
Those video objects can change, via AJAX; so you'll want to monitor for new objects.
There are some minor issues but first note that the entire existing script can be simplified to this, with jQuery:
// ==UserScript==
// #name CNN Download
// #namespace Cool
// #description CNN Download
// #include http://*cnn.com/video/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function insertlinks () {
var boxes = $(".sec_video_box");
boxes.each ( function () {
var theboxid = this.id;
$(this).append ('link');
} );
}
$(window).load (insertlinks);
(Important: This sample code will still not work.)
Handling the AJAX issues, it becomes:
// ==UserScript==
// #name CNN Download
// #namespace Cool
// #description CNN Download
// #include http://*cnn.com/video/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function insertlink (jNode) {
var theboxid = jNode.attr ('id');
jNode.append ('link');
}
waitForKeyElements (".sec_video_box", insertlink, false);
function waitForKeyElements (
selectorTxt, /* Required: The jQuery selector string that
specifies the desired element(s).
*/
actionFunction, /* Required: The code to run when elements are
found. It is passed a jNode to the matched
element.
*/
bWaitOnce, /* Optional: If false, will continue to scan for
new elements even after the first match is
found.
*/
iframeSelector /* Optional: If set, identifies the iframe to
search.
*/
)
{
var targetNodes, btargetsFound;
if (typeof iframeSelector == "undefined")
targetNodes = $(selectorTxt);
else
targetNodes = $(iframeSelector).contents ()
.find (selectorTxt);
if (targetNodes && targetNodes.length > 0) {
/*--- Found target node(s). Go through each and act if they
are new.
*/
targetNodes.each ( function () {
var jThis = $(this);
var alreadyFound = jThis.data ('alreadyFound') || false;
if (!alreadyFound) {
//--- Call the payload function.
actionFunction (jThis);
jThis.data ('alreadyFound', true);
}
} );
btargetsFound = true;
}
else {
btargetsFound = false;
}
//--- Get the timer-control variable for this selector.
var controlObj = waitForKeyElements.controlObj || {};
var controlKey = selectorTxt.replace (/[^\w]/g, "_");
var timeControl = controlObj [controlKey];
//--- Now set or clear the timer as appropriate.
if (btargetsFound && bWaitOnce && timeControl) {
//--- The only condition where we need to clear the timer.
clearInterval (timeControl);
delete controlObj [controlKey]
}
else {
//--- Set a timer, if needed.
if ( ! timeControl) {
timeControl = setInterval ( function () {
waitForKeyElements ( selectorTxt,
actionFunction,
bWaitOnce,
iframeSelector
);
},
500
);
controlObj [controlKey] = timeControl;
}
}
waitForKeyElements.controlObj = controlObj;
}
(Which does work.)
window.onload = insertlinks;
Remove the (), they cause the function to run immediately and the return value (null in this case) is assigned to onload. Locally, this is fine since loading is near-instant. Online, however, it will fail.

Greasemonkey: Change text in a webpage?

I used the function:
document.getElementsByTagName('strong')
to get all the text in a page with that type of formatting. The HTML looks like:
<td align="center" valign="bottom"><H1><font size="+4"><strong>TEXT_HERE</strong></font> <br>
I would like to change "TEXT_HERE" to maybe something else or remove it all together. How might I go about doing that?
Thanks in advance for your help :)
With a for loop?
var strongElems = document.getElementsByTagName('strong');
var wantToHide = true || false;
for (var i=0; i<strongElems.length; i++)
{
var thisElem = strongElems[i];
if (wantToHide)
{
thisElem.style.display = "none"; // hide it
}
else
{
thisElem.textContent = "something else"; // change it
}
}
// ==UserScript==
// #name MyScript
// #namespace http://example.com
// #description Example
// #include *
//
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js
// ==/UserScript==
var shouldHide = false;
$('strong').each(function() {
if(shouldHide) {
$(this).hide();
} else {
$(this).text("New Text");
}
});
When I wanted to change some text in a web page, I based my Greasemonkey solution on DumbQuotes. I liked that I could easily define replacement pairs into a list:
replacements = {
"old": "new",
"foo": "bar",
};
That said, I'll check out Tomalak's solution as well. Thanks for posting this question.

Categories