Replace specific table values using a Greasemonkey script |
this javascript code let's you replace the content of a TD by it's index
where 0 is the first element.
var tbl=document.getElementsByTagName("table")[0]; //get the first TABLE
var trs=tbl.getElementsByTagName('tr'); //get all TR's in that table
var replaceTD=function(TRindex,TDindex,value){
trs[TRindex].getElementsByTagName('td')[TDindex].innerHTML=value; //
replaced with innerText
};
to change the second TD of the first TR that is not a title (so the third)
your indexes will be TRindex=2 cause it starts from 0 ...
and the TDindex=1
and the function you will call is :
replaceTD(2,1,'WHATEVER');
|
Convert a greasemonkey Script after E4x is not supported |
If there is a dependency on e4x, try including the JavaScript
implementation:
e4x.js
As an alternative, here are other questions which cover mapping e4x syntax
to XPath or XML to JSON:
What is the Flex/AS3/E4X equivalent of this xpath query?
Howto convert E4X XML Elements into JSON Notation
In addition, you can continue to use e4x by accessing the data via yql:
Using e4x with yql
|
Including a Greasemonkey script across multiple domains |
Reference:
Greasemonkey Include and exclude rules
Match Patterns
Match patterns and globs
The solutions that work on Greasemonkey (which is Firefox), may be
different on Chrome and on Tampermonkey.
Three basic approaches:
Use 30 different @include lines: While this may be unpalatable in terms of
cut-and-paste coding, it is the one approach that will work the same across
browsers and the one that will have the best browser performance. The
other approaches require the browser to do (more) checks against possibly
every page or iframe visited.
Use a regex @include:
@include
/^http://(1stDomain.com|2ndDomain.com|3rdDomain.net|etc.)/(admin/edit|blog|user/.+?/history)/
This is one line, and performs fairly well, but the line can get unwieldy,
and this will only work on Greasemonkey an
|
jQuery .ready not getting called from within Greasemonkey script |
The alert doesn't fire for two reasons:
The browser is redirected from www.ted.com to www.youtube.com right away --
long before the ready event can fire on ted.com. The script is not set to
fire on youtube.com at all.
If you want the script to fire on both domains, adjust the @include (or
@match) directives and then use checks like:
if (location.hostname == "www.ted.com") {
var url = window.location.href;
var talk_name = url.split("/").pop();
talk_name = talk_name.substring(0,
talk_name.lastIndexOf('.html'));
var youtube_search_url =
'http://www.youtube.com/user/TEDtalksDirector/search?query=' + talk_name;
window.location.href = youtube_search_url;
}
to alter the script's behavior, per domain.
Because @grant none is used, the GM script's jQuery c
|
Prevent Greasemonkey script from inserting div into iframe |
if ( window.self === window.top ) { not in a frame } else { in a frame }
check the above condition first before your code of inserting div
original link:
How to identify if a webpage is being loaded inside an iframe or directly
into the browser window?
|
How to transform an XML file with XSLT, using a Greasemonkey script? |
I would have added this in a comment, but I don't have the relevant
reputation. There are two things that I would check. Especially if this is
working on a string, and not a file from the server like you said
Make sure that what you are getting from the server is a string, and not an
object
Make sure the xml you are getting from the server is correct.
If you aren't getting a string, you can do an ajax request to get the text
from the xml. And then load that as your new xml var.
And if you really just wanted to make your xml user friendly, I would
suggest checking out
http://code.google.com/p/vkbeautify
and
http://google-code-prettify.googlecode.com/svn/trunk/README.html
Those should maintain the xml format while stylizing it to make it easy to
read. Plus, you won't have to mess with
|
Click many links, in one page, with a Greasemonkey script? |
var all = document.getElementsByClassName("delete");
for(var i=0; i<all.length; i++) {
var deleteUrl = all[i].href;
var ifr = document.createElement("IFRAME");
document.body.appendChild(ifr);
ifr.src = deleteUrl;
}
You could run a simple script like the above in the browser's JavaScript
console or make it a bookmarklet.
|
Greasemonkey script seems to execute lines out of order |
Try this ..
setTimeout(function(){$("#cat_1").attr("checked",true);},0);
If it is a race condition of some kind this will put your command at the
bottom of the stack.
|
Watch for element creation in greasemonkey script? |
MutationObservers are called for more things than just adding nodes,
including changes to attributes and removing nodes.
So watch out for mutation.addedNodes returning null - in which case this
code will fail. Try:
if (mutation.addedNodes &&
mutation.addedNodes[0].getAttribute('class') === 'nav') {
...
The mutation object also has a 'type' attribute that you can use to get
more info; have you read the API docs on MDN? There are some good examples
there.
|
Greasemonkey script does not load external JS and CSS file |
That linked answer was from 2011, and Greasemonkey has changed a lot since
then. (Note, I just now updated that answer to reflect the changes.)
Basically, you need to use @grant directives now. If you looked on
Firefox's error console (CtrlShiftJ), you might have seen error messages
like:
GM_addStyle is not defined
Here is a bare-bones addition of jQuery-UI to demonstrate the process:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require
http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js
// @resource jqUI_CSS
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css
// @grant GM_addStyle
// @grant GM_getResou
|
addEventListener and setInterval fail silently in a Greasemonkey script |
Update (Now that target page was given):
The question code did not match the structure of the actual page. It
typically would throw TypeError: iTags[3] is undefined errors.
Using DOM methods, to get the desired info, does the job. A working script
is:
// ==UserScript==
// @name _KROQ, song info to page title
// @include http://betaplayer.radio.com/player/*
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
if (window.top != window.self) //-- Don't run on frames or iframes.
return;
window.addEventListener ('load', function () {
setInterval (setTitle, 5000);
}, false);
function setTitle () {
var songInfoNode = document.querySelector (
"#play_info
|
"TypeError: can't convert undefined to object" with GreaseMonkey script |
You are using .trigger() incorrectly, you need to pass at least the event
type argument.
$('#triggerAllButton').click(function(e){
e.preventDefault();
$(".btn.trigger").trigger("click"); //.each is implicit on all jQuery
methods
});
|
Add images and a mouseover event in a loop, in a Greasemonkey script? |
Do not use anonymous functions in a loop like that. That leads to memory
and performance problems.
Anyway, use the return value of insertBefore(). like so:
var anchors = document.evaluate (
'//a[@target]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
var icon4 = document.createElement('img');
icon4.src = '...';
for (var a = 0; a < anchors.snapshotLength; a++) {
if (anchors.snapshotItem(a).href.substring(0, 16) !=
location.href.substring(0, 16)) {
var newNode = anchors.snapshotItem(a).parentNode.insertBefore (
icon4.cloneNode (true), anchors.snapshotItem (a)
);
newNode.addEventListener ('mouseover', myMouseInOutHandler, false);
newNode.addEventListener ('mouseout', myMouseInOutHandler, false);
}
}
funct
|
Injecting a document.write call from a Greasemonkey script causes nothing to load |
The smartest/best(est) thing to do is to avoid document.write(). Use DOM
techniques. Here's a complete script:
// ==UserScript==
// @name _Replace a target page using DOM techniques
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var D = document;
var newDoc = D.implementation.createHTMLDocument ("");
D.replaceChild (
D.importNode (newDoc.documentElement, true),
D.documentElement
);
D.body.innerHTML = '<h1>TEST</h1>'
Greasemonkey normally fires on DOMContentLoaded, not when the page has
fully completed loading. Chrome fires later than that, by default.
Anyway, at DOMContentLoaded, in
|
Adding javascript to a XML file transformed with XSLT using a Greasemonkey script |
Don't use onclick. This goes triple for userscripts, as there are
additional scope and/or sandbox conflicts.
Also, it's a poor idea to try and add JS into the XSLT file/text, and there
is no need for script injection in this case either.
Use the script to do whatever JS manipulation you have in mind. For
example:
// ==UserScript==
// @name _XML Renderer with javascript functionality
// @description Stylesheet and javascript for xml results
// @include http://YOUR_SERVER.COM/YOUR_PATH/*.xml
// @resource xslFile Q_17998446_transform.xsl
// @grant GM_getResourceText
// ==/UserScript==
var xsl_str = GM_getResourceText ("xslFile");
var processor = new XSLTProcessor ();
var dataXSL = new DOMParser ().parseFromString (xsl_str, "text/xml");
processor.importSty
|
Get client information from a Greasemonkey script (local machine name, Firefox profile) |
No. You cannot read the local machine name, nor Firefox profile name, nor
Firefox profile directory using javascript or Greasemonkey.
If you could access this information, it would be at least a "sec-moderate"
security breach. So, if you figure out a hack for this, let us know
immediately, so we can shut you down. ;)
|
replace href and url by the tag |
Notepad++:
You could use this in find:
href="([^"<]{2,}")
And in replace, you can use:
href="<c:url value="/fo/1 />"
^^
The ^^ indicate where the captured group is being inserted.
EDIT: To match both href and src, you will use this:
(href|src)="([^"<]{2,}")
And replace:
1="<c:url value="/fo/2 />"
|
PHP: How can you remove/replace a specific href attribute value |
You could try something like the following in PHP:
$newtext = preg_replace('/^("http://cdn.example.com/){1}(.*)("){1}$/', '"#"
class="disabled-link"', $oldtext);
$oldtext being your input article as a string.
$newtext being the text to echo on the page.
Broken down:
Find text starting with "http://cdn.example.com/
Then match anything
Stop at "
Replace with "#" class="disabled-link"
This should let you remove the link and also I added the class part so that
you can add some CSS to style the links as text.
Example:
.disabled-link{
color:#000;
pointer-events: none;
cursor: default;
text-decoration: none;
}
All this combined will provide users with a link that is completely
invisible without looking into the DOM or the source.
|
replace href attribute in anchor element |
I am assuming you have some frontend (CMS?) access and no direct file
access.
You can put it in the head section of every document.
function fixLinks(){
var links = document.getElementsByTagName('a');//Get all links
for(i = 0 ; i<links.length ; i++){//Loop throught links
var curLink = links[i].href // Cache
links[i].href = curLink .replace('mysite','mynewsite');//Replace mysite
with my newsite and return the fixed string
}
}
window.onload = fixLinks;
|
replace matching text in hyperlink href |
You don't need a regular expression, just do a normal string replace:
http://jsfiddle.net/9MXSZ/
$('a').each( function() {
var $this = $(this);
var href = $this.attr('href').replace('chapter','chapter_af');
$this.attr('href', href );
});
If you really want to use a regex, the in your version is throwing it off:
.replace(/chapter/,'chapter_af')
|
Replace all links(href) in a web page using jquery |
Try this:
$('a[href*="sites.com"]').each(
function(){
// Do a substring here to keep the beginning of the path (domain)
$(this).attr("href", "http://any.sites.com/");
})
|
How can I replace “<” and “>” with “<” and “> except and text tags in Perl |
You can try this straightforward approach:
$a =~ s/</</g;
$a =~ s/>/>/g;
# Fix "a" & "img"
$a =~ s/<as(.*?)>(.*?)</a>/<a
$1>$2</a>/g;
$a =~ s/<imgs(.*?)>/<img $1>/g;
Note:
[^img|a] is not i,m,g,a or |
If you need to find < not followed by img or a - use negative lookahead:
/<(?!img|a)/
|
How to replace a href link within a Textarea with jQuery |
This is an example; after loading the href will get replaced:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function () {
var textarea =
document.getElementsByTagName("textarea")[0];
textarea.innerHTML =
textarea.innerHTML.replace(
/href=".*"/,
"http://www.stackoverflow.com");
}
</script>
</head>
<body>
<textarea><a
href="http://www.google.com"></a></textarea>
</body>
</html>
|
jQuery + regular expression to replace href and src values inside textarea |
You don't need a regex to do that. You just have to concatenate the current
url and the website url.
$('textarea').each(function(){
var obj = $(this);
obj.find('a').attr('href', 'http://www.sitename.com' +
obj.find('a').attr('href'));
obj.find('img').attr('src', 'http://www.sitename.com' +
obj.find('img').attr('src'));
});
|
add location.href to a script src |
You can use the createElement:
var link = "http://example.com/script.js?ref="+location.href;
script1 = document.createElement('SCRIPT');
script1.type="text/javascript";
script1.src = src1;
document.head.appendChild(script1);
EDIT:
If you can append the script in the head or body putting
document.head.appendChild(script1);
or
document.body.appendChild(script1);
But if you can put in the specific point (id of one div or input), you can
put with:
document.getElementById("NAMEOFID).appendChild(script1);
|
How can I execute a script after calling window.location.href? |
You are redirecting the browser with window.location.href and I'm afraid as
you are purely just changing the browser's location, you can't have any
affect/input on the page you are moving to (unless you use query string
parameters and then create content with something like PHP
(myurl.php?newcontent=whatever) )
|
How to have an href process in an iframe (colorbox) after running a php script? |
Why don't you try something like the done function of an ajax request
something like:
$.ajax({
type: "POST",
url: "featureimagesave.php",
data: {
imgBase64: dataURL,
yogatextcolor: txtcolorsel,
yogamatcolor: selmatcolor,
prefile: prefile,
name: matname,
price: priceCalc
},
}).done(function ( data ) {
//do your colorbox logic
});
This are jQuery's promise callbacks and work I think as of jQuery 1.5, for
more info you could see jquery's API http://api.jquery.com/jQuery.ajax/
|
trigger('click') doesn't work on anchors without an actuall link in the href ( js function in the href attrbute ) |
trigger('click') will only invoke attached event handlers; if you have
JavaScript hrefs, they won't be triggered.
You could try attaching regular click handlers to your links, or you could
do something like this instead:
var idFormat = /confirm_(d+)/;
$('.confirm_btn').each(function() {
var btn = $(this);
var id = parseInt(idFormat.exec(btn.attr('id'))[1], 10);
confirm_ajax(id);
});
|
Replace script URL though the console |
You can create script tag using javascript in console using the following
code:
var js = document.createElement('script');
js.async = true;
js.src = "js/tiny_mce/tiny_mce.js";
document.body.appendChild(js);
and if you want to update it you already have it's reference so you can
update it using
js.src = "somethingelse.js";
Hope that helps....
|
Shell Script: grep and replace |
Change this line:
sed -e "s/down/up/g" test.htm
To this:
sed -i -e "s/down/up/g" test.htm
The -i flag means to edit the file "in-place" rather than to write the
replacements to standard output.
|
shell script : how to replace file name |
Created using bash on a mac, so it might work with whatever shell you are
using...
string="/home/guest/test"
echo $string | sed 's//([^/]{0,})$//.1.log/'
Using simple shell string replacement wasn't going to work since I know of
no way you can target the last occurrence of the / sign as the only
replacement.
Update:
Actually I came to think of a alternative way if you know that it is always
"/two/directories/in"
string="/home/guest/test"
firstpartofstring=$(echo $string | cut -d/ -f1-3)
lastpartofstring=$(echo $string | cut -d/ -f4)
echo ${firstpartofstring}/.${lastpartofstring}.log
|
shell script: replace the contents |
try this: (save it to your main.sh):
#!/bin/ksh
awk -F: -v a="$1" -v i="$2" 'NR==1{n=$2;print $1":"a"-"i;next}{print
$1":"n}' /VersionInfo.properties > /tmp/tmpVersion && mv
/tmp/tmpVersion VersionInfo.properties
try with
main.sh "13.7.0" "4"
|
How to make sed script replace in file? |
If your sed supports -i option then you can run your script like this:
./fix.sh -i myfile.txt
-i option of sed does the in-file substitutions.
If your version of sed does not support the -i option then you can do the
following which is pretty much the same thing that -i does behind the
scene:
./fix.sh myfile.txt > temp && mv temp myfile.txt
Why redirecting to the same file doesn't work?
The reason is that the redirection opens the file for writing and ends up
clearing any existing contents. sed then tries to read this empty file, and
does nothing. The file is then closed and there by you get an empty file.
|
Batch Script to replace line in an .ini |
This should help you out.
@echo off
set "var="
set /p "var=Enter 1 for NY, 2 for DC or 3 for LA"
if "%var%" EQU 1 (
>c:samplefile.ini echo 10.0.0.0
>>c:samplefile.ini abcde
)
if "%var%" EQU 2 (
>c:samplefile.ini echo 20.0.0.0
>>c:samplefile.ini abcde
)
if "%var%" EQU 3 (
>c:samplefile.ini echo 30.0.0.0
>>c:samplefile.ini abcde
)
echo Good luck - I hope you entered the right number! :)
|
can dart replace php serverside script ? |
Probably not.
First of all, dart:html can't be used on the server side. This may or may
not be a problem in your case.
More importantly, LAMPP doesn't parse JavaScript - it's treated as a pure
client language.
You'd need an alternative that is able to parse JavaScript on the server
side, for example node.js, but I don't think node.js will be able to parse
your PHP scripts.
Another alternative: Run the Dart server in Dart's VM. You'd still need
another port for it, but at least there is no need for the "JS server".
|
Script to replace variables used in simulink blocks with a value |
Not sure if this will work, but can you combine Simulink.findVars with
get_param to get all the block parameters for each of the blocks identified
by Simulink.findVars? As per Get a Block Parameter Value and Attributes:
block_parameters = get_param(block_path,'DialogParameters')
You could then fgifure out which parameter each variable (e.g. gain_A) is
used for.
|
How to replace command name when invoking as bash script? |
I would leave the git-receive-pack symlink alone, instead create a bash
function (in ~/.bashrc). Something like this should do the trick:
function git-receive-pack() {
... (do your stuff)
command git-receive-pack $*
}
|
javascript replace() Method for NOWRAP, and Script |
Judging by given markup, following JS code should make the replacement:
<script>
document.getElementsByClassName("myWinError")[1].parentNode.innerHTML =
'Кот Шредингера <span
class="myWinError">*</span>';
document.getElementsByClassName("myBtnCont")[0].firstChild.innerHTML =
'Заправить';
</script>
|
Using sed in bash script to replace LaTeX aliases |
Code for GNU sed:
sed -r '/^%/d;s#.*({\w+})({.*})#1 2#;s#\#\\#g;s#(S+)s(S+)#\|1|s|1|2|g#'
file1|sed -f - file2
$ cat file1
% a
ewcommand{ao}{$^{18}$O}
ewcommand{aodso}{$^{18}$O/$^{16}$O}
% b
ewcommand{ea}{egin{equation}}
ewcommand{eaa}{egin{eqnarray}}
% c
ewcommand{cthree}{C$_3$}
ewcommand{cfour}{C$_4$}
ewcommand{coz}{CO$_2$}
$ cat file2
This is my test {ao}
{aodso} my test is this
Does it work {ea}
{eaa} test test test
work work work {cthree}
{cfour} This is my test
my test is this {coz}
$ sed -r "/^%/d;s#.*({\w+})({.*})#1 2#;s#\#\\#g;s#(S+)s(S+)#\|1|s|1|2|g#"
file1|sed -f - file2
This is my test {$^{18}$O}
{$^{18}$O/$^{16}$O} my test is this
Does it work {egin{equation}}
{egin{eqnarray}} test test test
work work work {C$_3$}
{C$_4$} This is my test
my test is th
|
I can't make a search-and-replace script for Python |
One simple way to do this is with the open function and the os module:
import os
with open(tmp_file) as tmp:
with open(my_file) as f:
for line in f.readlines():
tmp.write(line.replace("oldString1",
"newString1").replace("oldString2", "newString2") + "
")
os.remove(my_file)
os.rename(tmp_file, my_file)
|