Redirecting multiple values in URL with Greasemonkey - javascript

I'm trying to get Greasemonkey to automatically redirect a page when it hits a certain URL, and redirect to a page with two of the same values. For instance:
http://www.google.com/page=438985&view=49834
into: http://www.google.com/document/page=438985/field&view=49834&DONE
I've tried the following:
var links,thisLink;
links = document.evaluate("//a[#href]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
for (var i=0;i<links.snapshotLength;i++) {
var thisLink = links.snapshotItem(i);
thisLink.href = thisLink.href.replace(RegExp('http://www.google.com/page=($1)&view=($2)'),
'http://www.google.com/document/page=$1/field&view=$2&DONE');
}

var links = document.getElementsByTagName('a');
for(var i = links.length - 1; i >= 0; i--) {
if(links[i] && links[i].href) {
links[i].href = links[i].href.replace(/http:\/\/www\.google\.com\/page=(\d+)&view=(\d+)/,
'http://www.google.com/document/page=$1/field&view=$2&DONE');
}
}
Demo

Related

Looping through layers and setting them to visible

I'm trying to loop through the layers in an InDesign doc and set all of them to visible. This is to ensure that file collection occurs correctly.
I put together the following
var myDocument = app.activeDocument;
//make all layers visable
for (i = 0; i < myDocument.layers.length; i++) {
if(myDocument.layers[i].visible = false) {
myDocument.layers[i].visible = true;
};
};
This is excerpted from a larger script that automates the file collect, this is just the routine for the layers.
For context here's the actual script.
function Left(str, n){
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else
return String(str).substring(0,n);
}
function Right(str, n){
if (n <= 0)
return "";
else if (n > String(str).length)
return str;
else {
var iLen = String(str).length;
return String(str).substring(iLen, iLen - n);
}
}
if (app.documents.length != 0){
var myDocument = app.activeDocument;
var docName = myDocument.name;
var docName = Left(docName, String(docName).length-5)
//alert(docName);
var myFolder = new Folder ("~/Desktop/"+docName+"/");
//myFolder.create("Bob");s
/*new Folder ("~/Desktop/Collected/Hi-Res PDF/");
new Folder ("~/Desktop/Collected/RELEASE INFO/");*/
//make all layers visable
for (i = 0; i < myDocument.layers.length; i++) {
if(myDocument.layers[i].visible = false) {
myDocument.layers[i].visible = true;
};
};
myDocument.packageForPrint (myFolder,1,1,0,1,0,0,0);
var newFolder = new Folder ("~/Desktop/"+docName+"/RELEASE INFO/");
newFolder.create();
var inddFolder = new Folder ("~/Desktop/"+docName+"/Indesign Files/");
inddFolder.create();
var newFolder = new Folder ("~/Desktop/"+docName+"/IDML Files/");
newFolder.create();
//Export IMDL File
myDocument.exportFile(ExportFormat.INDESIGN_MARKUP, File("~/Desktop/"+docName+"/IDML Files/"+docName+".idml"), false);
//Move INDD File
//var myInddfile = File("~/Desktop/"+docName+"/"+docName+".indd");
//myDocument.changePath(File(inddFolder),false);
//Rip Low Res PDFs
var myPDFExportPreset = app.pdfExportPresets.item("CP3 Low Rez");
app.activeDocument.exportFile(ExportFormat.pdfType,
File("~/Desktop/"+docName+"/RELEASE INFO/"+docName+"_LR.pdf"), false, myPDFExportPreset);
//Now export the document. You'll have to fill in your own file path.
//app.activeDocument.exportFile(ExportFormat.pdfType, File("~/Desktop/"+docName+"_FILM/RELEASE INFO/"+docName+"_LR.pdf"), false);
var newFolder = new Folder ("~/Desktop/"+docName+"/Hi-Res PDF/");
newFolder.create();
//Rip Hi-Res PDF
var myPDFExportPreset = app.pdfExportPresets.item("Kern Hi Rez Print");
app.activeDocument.exportFile(ExportFormat.pdfType,
File("~/Desktop/"+docName+"/Hi-Res PDF/"+docName+"_HiRes.pdf"), false, myPDFExportPreset);
//Now export the document. You'll have to fill in your own file path.
//app.activeDocument.exportFile(ExportFormat.pdfType, File("~/Desktop/"+docName+"_FILM/Hi-Res PDF/"+docName+"_HiRes.pdf"), false);
myFolder.execute();
}
else{
alert("Please open a document and try again.");
}
Hopefully, when the script executes, all the layers will be set to visible then the file collect will occur.
Use triple equals in your if statement for strict equality. For instance:
for (i = 0; i < myDocument.layers.length; i++) {
if(myDocument.layers[i].visible === false) { // <-- Note the `===` instead of `=`
myDocument.layers[i].visible = true;
};
};
Or even better, you can change it to utilize the Logical NOT ! operator
for (i = 0; i < myDocument.layers.length; i++) {
if (!myDocument.layers[i].visible) { // <-- Change to this.
myDocument.layers[i].visible = true;
};
};
Note: Given your example, the conditional if statement is not actually necessary. You could simply do this instead:
for (i = 0; i < myDocument.layers.length; i++) {
myDocument.layers[i].visible = true;
};
Set everything to be visible
If you actually want to make everything visible - including; InDesign document layers and all page items on the sub-layer(s), then you'll need to do something like this example:
var myDocument = app.activeDocument;
// ...
function makeAllVisible() {
for (i = 0, max = myDocument.layers.length; i < max; i++) {
var currentLayer = myDocument.layers[i];
currentLayer.visible = true; // Make the top level layer visible.
// Make all sub layers visible,
// i.e. make all page items on the current layer visible.
var currentLayerPageItems = currentLayer.allPageItems;
for (x = 0, len = currentLayerPageItems.length; x < len; x++) {
currentLayerPageItems[x].visible = true
}
}
}
makeAllVisible(); // Invoke the function.
// ...

Ask user if external link should be opened in an external window / tab

I have the following Javascript running on my site to open all external links in a new window / tab:
function linkopener(a) {
var b = a ? "_blank" : "_self";
var c = document.links;
for (var i=0; i < c.length; i++) {
if (c[i].href.search("domain.tld") == -1) c[i].target = b;
}
}
window.onload = linkopener;
Now I would like to add a question to the user as soon as she/he clicks on an external link whether she/he wants to open it in a new window/tab or open it in the current window/tab.
No question should be shown if she/he wants to exit the site manually.
Is that possible and if yes, how?
Thanks in advance!
function linkopener(a) {
var b = a ? "_blank" : "_self";
var c = document.links;
for (var i = 0; i < c.length; i++) {
if (c[i].href.search("peleke.de") == -1) {
c[i].addEventListener("click", function () {
if (confirm("Do you want to open this in a new window/tab?")) {
this.target = b;
} else {
this.target = '';
}
});
}
}
}
window.onload = linkopener;
DEMO

passing page scraped data in the URL

In my Chrome extension, I'm trying to scrape information from the current tab (in content.js) and send it as parameter to the provided URL (background.js). It seems like I can scrape everything from the tab and append it to the URL except the values of input tags. Here's my code:
content.js:
var elements = new Array("form","h1","input","td","textarea","time","title","var");
//declare an array for found elements
var foundElements = new Array();
//declare an array for found ids
var foundIds = new Array();
//this counter is used to hold positions in the element array.
var elementCounter = 0;
//this counter is used to hold positions in the foundIds array
var idsCounter = 0;
//this counter is used to hold positions in the classCounter array.
var classCounter = 0;
//and we're going to output everything in a giantic string.
var output = "URL=" + document.URL;
//scrape the page for all elements
for (var i = 0; i < elements.length; i++)
{
var current = document.getElementsByTagName(elements[i]);
if(current.length>0)
{
for (var z=0; z<current.length; z++)
{
var inTxt = current[z].innerText;
output += "&" + elements[i] + "=" + inTxt;
}
elementCounter++;
//now that we have an array of a tag, check it for IDs and classes.
for (var y = 0; y<current.length; y++)
{
//check to see if the element has an id
if(current[y].id)
{
//these should be unique
var hit = false;
for (var x = 0; x<foundIds.length; x++)
{
if(foundIds[x]==current[y].id)
{
hit=true;
}
}
//if there was no hit...
if(!hit)
{
foundIds[idsCounter]=current[y].id;
idsCounter++;
var currVal = current[y].value;
output+="&" + current[y].id + "=" + currVal;
}
}
//now we pull the classes
var classes = current[y].classList;
if(classes.length>0)
{
for (var x = 0; x<classes.Length; x++)
{
var hit = false;
for (var z = 0; z<foundClasses.length; z++)
{
if(foundClasses[z]==classes[x])
{
hit=true;
}
}
//if there was not a hit
if(!hit)
{
foundClasses[classCounter]=classes[x];
classCounter++;
output+="&" + classes[x] + "=";
}
}
}
}
}
}
chrome.runtime.sendMessage({data: output});
background.js:
var output2;
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
output2 = "text_input1=";
output2 += request.data;
});
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.create({url: "http://www.google.com?" + output2}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
sendMessage();
});
});
});
Does anyone know why the input tags values are passed as blank?
Because you're trying to get the input text by using current[z].innerText.
However, you have to use current[z].value for inputs.

Open external links in a new tab without jQuery

What's the best way to open all external links (URLs that don't match the current domain) in a new tab using JavaScript, without using jQuery?
Here's the jQuery I'm current using:
// Open external links in new tab
$('a[href^=http]').click(function () {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
window.open(this.href);
return false;
}
});
Pure JS:
function externalLinks() {
for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
var b = c[a];
b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
}
}
;
externalLinks();
The links property returns a collection of all <area> and <a> elements in a document with a value for the href attribute.
var links = document.links;
for(var i = 0; i < links.length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Document/links
Add a target="_blank" to the tag. You could do that in the pre-processor (e.g. PHP) or in a JS during the onload event.
$("a[href^=http]").each(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank",
title: "Opens in a new window"
});
}
})
This script should work for you.
UPDATE : try this fiddle http://jsfiddle.net/sameerast/GuT2y/
JS version
var externalLinks = function(){
var anchors = document.getElementsByTagName('a');
var length = anchors.length;
for(var i=0; i<length;i++){
var href = anchor[i].href;
if(href.indexOf('http://sample.com/') || href.indexOf('http://www.sample.com/')){
return;
}
else{
anchor[i].target='_blank';
}
}
};

How to Convert this Greasemonkey code to JavaScript for Android?

I am trying to load a page and then run a javascript code on it, I found a Greasemonkey script that does the same, but I am having problems implementing the same thing in android, probably because I don't know anything about javascript.
This is the Greasemonkey script; it's supposed to a give a new link:
window.addEventListener("load", function ()
{
var link = document.evaluate("//div[#class='dl_startlink']/div/a[contains(#href,'"+window.location.href.match(/\?(.*)$/)[1]+"')]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
if( !link.snapshotLength )
return;
location.href = link.snapshotItem(0).href;
}, false);
and this is how I want to run it:
public void onPageFinished (WebView view, String url) {
System.out.println("webview loaded");
webView.loadUrl("javascript:/*...........Javascript code here........*/");
}
Any ideas on how I get that link and load that page in the webview?
EDIT: Another version does the same thing.
var candidates = document.evaluate("//*[#class = 'dl_startlink']/div", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
if( !candidates.snapshotLength )
return;
//The DIV with the highest zIndex has the *real* link; the rest are useless.
- var maxDiv = candidates.snapshotItem(0);
- for( var i = 1; i < candidates.snapshotLength; i++ )
- if( maxDiv.style.zIndex < candidates.snapshotItem(i).style.zIndex )
- maxDiv = candidates.snapshotItem(i);
- location.href = maxDiv.children[0].href;
Ok, here's only simple Xpath query, which may be rewritten as CSS selector.
Also I decided to replace window.location.href.match(/\?(.*)$/)[1]. If my version will not work, replace first 2 lines with var query = window.location.href.match(/\?(.*)$/)[1];.
Actually, maybe even var query = window.location.search.replace(/^\?/,'') is enough.
window.addEventListener("load", function ()
{
var l = window.location;
var query = l.search ? (l.search.replace(/^\?/,'') + l.hash) : ""
var link = document.querySelector("div.dl_startlink > div > a[href='" + query + "']");
if (!link) return;
l.href = link.href;
}, false);
New code for Android:
var candidates = document.querySelector("div.dl_startlink > div");
if( !candidates.length)
return;
//The DIV with the highest zIndex has the *real* link; the rest are useless.
var maxDiv = candidates[0];
for( var i = 1; i < candidates.length; i++ )
if( maxDiv.style.zIndex < candidates[i].style.zIndex )
maxDiv = candidates[i];
location.href = maxDiv.children[0].href;
Compacted version:
webView.loadUrl("javascript:window.addEventListener('load',function(){var%20candidates=document.querySelector('div.dl_startlink>div');if(!candidates.length)return;var maxDiv=candidates[0];for(var%20i=1;i<candidates.length;i++)if(maxDiv.style.zIndex<candidates[i].style.zIndex)maxDiv=candidates[i];location.href=maxDiv.children[0].href;},false)");

Categories