syntaxis on matching urls from an array saved on extension storage - javascript

I have been going through the Google chrome APIs in order to work on an extension and the processes regarding it. I stumbled upon the chrome.webRequest https://developer.chrome.com/extensions/webRequest#event-onBeforeRequest I have been tinkering with the syntax but I am lost with it because I'm relatively new to programming and using the chrome APIs
What I was thinking was using chrome.webRequest.onBeforeRequest.addListener(function callback) and then making it use chrome.tabs.remove to remove the tab is it matches the array but I am not sure how to do that
I have this for the removing of the tab using the google chrome match filters
var urlArray= ["*://facebook.com/*", "*://example.com/*", "*://google.com/*" ];
chrome.tabs.onCreated.addListener(function (tab) {
for (var i = 0, len = urlArray.length; i < len; i++) {
if (tab.url.indexOf(urlArray[i]) > -1) {
chrome.tabs.remove(tab.id);
alert("things");
break;
}
}
});

The problem in your code is that, if you check for "*somestring*", the .indexOf() function will actually look for that exact string, meaning that asterisks aren't used as a wildcard, and will only match if the string contains them.
Here's an example:
"hello".indexOf("*hello") // -1 there's no *
"123hello".indexOf("*hello") // -1 there's no *
"*hello".indexOf("*hello") // 0 here it is, in the first position
"123*hello".indexOf("*hello") // 3 and again, in the fourth position
So, in your case, you should use Regular Expressions, like this:
var urlExp= /https?\:\/\/(facebook|google|example)\.com/i;
chrome.tabs.onCreated.addListener(function (tab) {
if (urlExp.test(tab.url)) {
chrome.tabs.remove(tab.id);
alert("things");
}
});

Related

Reordering/move pages using Indesign script

I have a nearly 400 page document that I need to [randomly] reorder the pages. (If you need to know, this is a book of single page stories that need to be randomly distributed. I created a random list of pages to input into the script.)
I've been working with a modified script I found elsewhere on the internet that creates an array and moves the pages around:
var order="...list of new page numbers...";
// Create an array out of the list:
ranges = toSeparate (order);
if (ranges.length != app.activeDocument.pages.length)
{
alert ("Page number mismatch -- "+ranges.length+" given, "+app.activeDocument.pages.length+" in document");
exit(0);
}
// Consistency check:
sorted = ranges.slice().sort(numericSort);
for (a=0; a<sorted.length-1; a++)
{
if (sorted[a] < sorted[a+1]-1 ||
sorted[a] == sorted[a+1])
alert ("Mismatch from "+sorted[a]+" to "+sorted[a+1]);
}
// alert ("New order for "+order+"\nis "+ranges.join(", "));
// Convert from 1..x to 0..x-1:
for (moveThis=0; moveThis<ranges.length; moveThis++)
ranges[moveThis]--;
for (moveThis=0; moveThis<ranges.length; moveThis++)
{
if (moveThis != ranges[moveThis])
{
try{
app.activeDocument.pages[ranges[moveThis]].move (LocationOptions.BEFORE, app.activeDocument.pages[moveThis]);
} catch(_) { alert ("problem with page "+moveThis+"/index "+ranges[moveThis]); }
}
for (updateRest=moveThis+1; updateRest<ranges.length; updateRest++)
if (ranges[updateRest] < ranges[moveThis])
ranges[updateRest]++;
}
function toSeparate (list)
{
s = list.split(",");
for (l=0; l<s.length; l++)
{
try {
if (s[l].indexOf("-") > -1)
{
indexes = s[l].split("-");
from = Number(indexes[0]);
to = Number(indexes[indexes.length-1]);
if (from >= to)
{
alert ("Cannot create a range from "+from+" to "+to+"!");
exit(0);
}
s[l] = from;
while (from < to)
s.splice (++l,0,++from);
}} catch(_){}
}
// s.sort (numericSort);
return s;
}
function numericSort(a,b)
{
return Number(a) - Number(b);
}
This code worked, except that it was consistently rearranging them into the wrong random order, which, at the end of the day, is workable, but it'll just be a bigger pain in the ass to index the stories.
I suspected the problem might be caused by starting at the begginning of the document rather than the end, so I modified the script to start at the end, but then app.activeDocument.pages[ranges[moveThis]] kept coming up as undefined.
So I gave up and tried this:
app.activeDocument.pages[298].move (LocationOptions.BEFORE, app.activeDocument.pages[366]);
app.activeDocument.pages[33].move (LocationOptions.BEFORE, app.activeDocument.pages[365]);
app.activeDocument.pages[292].move (LocationOptions.BEFORE, app.activeDocument.pages[364]);
And so on for every page. (This reminds me of my time in junior high using sendKeys to create programs in Visual Basic. Had I bothered to seriously learn JavaScript instead of creating shitty AOL chatroom scrollers, I probably wouldn't be on here today.)
Nevertheless, I received the following error:
Error Number: 30477
Error String: Invalid value for parameter 'reference' of method 'move'. Expected Page or Spread, but received nothing.
I'm trying to avoid having to manually move the pages, especially considering the amount of time I've already been working on this. Any suggestions on what I need to change? Thank you!
The issue might be that you are using more than one page per spread and then trying to shuffle them across spread. The better way is to use single page per spread.
Here is a small snippet that works on my machine
var doc = app.activeDocument;
doc.documentPreferences.facingPages = false;
for (var i =0; i < 100; i++){
var index = parseInt((Math.random() * doc.spreads.length) % doc.spreads.length + '' , 10);
doc.spreads[index].move();
}
What this does is
Disables the facing pages options and makes one page per spread. A desirable condition as you mentioned that your stories are one page each(I am assuming that your stories will not violate this assumption).
Takes a random spread from the doc and sends it to the end of the spreads in the doc. It does so 100 times.
The result is what you wanted. A script to shuffle the current SPREADS randomly.

If Statement Have A String And Other String (Make To List)

Sorry i cant find the tutorial in google because i dont know the keyword...
var currentURL=location.href;
var str = currentURL;
if(str == "http://web.com/blabla" || str == "http://web.com/bleble"){
window.location = "http://web.com/ban";
} else {
}
How to make str == "http://web.com/blabla" || str == "http://web.com/bleble" to list ? so if i want to input some url again, i just input the url to the list. Can give me the code or link tutorial ???
Basically you'll need to place all of your URL's into an array and then iterate over the array checking each item.
var urls = ['http://web.com/','http://web.net/','http://web.org'];
var current_url = '...';
for (var i = 0; i < urls.length; i++){
if (current_url == urls[i]){
window.location = "http://web.com/ban";
break; // exit the loop since we have already found a match
}
}
The break command will terminate the loop and stop searching the array for matching URLs. Since the action you want to take needs to happen if any of the URLs match, it's enough for one to match in order to stop searching.
Lists are called arrays in javascript, and are declared using square brackets, like this: var badUrls = ["http://web.com/blabla", "http://web.com/bleble"].
To check whether the current URL appears in the array, you can use the .indexOf function of the array, which will return the first position in the array where the string you provide can be found (starting with 0 for the first element), or -1 if it doesn't exist. For example, if you have an array var arr = ["foobar", "foo", "bar", "baz"], and you do arr.indexOf("foo"), you get 1 because it's the 2nd element in the array. If instead you do arr.indexOf("fooba"), you will get -1 because none of the elements in the array are fooba exactly. In your code, you want to redirect the user if badUrls.indexOf(str) > -1. You can get more information on indexOf in the MDN Documentation.
That makes your code look like:
var currentURL=location.href;
var str = currentURL;
var badUrls = ["http://web.com/blabla", "http://web.com/bleble"]
if(badUrls.indexOf(str) > -1){
window.location = "http://web.com/ban";
} else {
}
window.location is a browser object, it you want the page to go to http://web.com/ban, you should use
window.location.href = "http://example.com/ban";
However, it looks like you are trying to prevent people from visiting pages using JavaScript. This is extremely insecure, because anyone that lists your code will see which URLs you're trying to protect and immediately request them. If they request those URLs with JavaScript disabled, or using curl, the pages will be delivered.
You should protect the pages with server side configuration. With Apache, you can use the Allow/Deny configuration or RewriteRules.

How to use doc.location.href.search within an array

I'm creating a basic Firefox plugin with which I want to block certain domain names and let them redirect to another external webpage.
How can I let 'doc.location.href.search' search within the VAR 'blockedSites' ?
(And if anyone knows how to fix the problem where Firefox loads the correct redirect-website, but in fullscreen-mode removing all tabs, would be welcome aswell)
This is the code so far:
onPageLoad: function (aEvent) {
var doc = aEvent.originalTarget;
var blockedSites=["domain1.com","domain2.net","domain3.org"];
if (doc.location.href.search("blockedSites") > -1)
{
window.location = "http://redirect-to-this.com"
}
Use indexOf instead of search:
if (blockedSites.indexOf(doc.location.href) >= 0)
indexOf will return the position the string in the array, so it must be 0 or greater to be an blocked site.

How To Join Relative URLs in JavaScript

I want to join two strings each representing a relative URL in Javascript.
I want to join the base URL http://www.adress.com/more/evenmore with the following examples:
../../adress (with the expected output: http://www.adress.com/adress)
../adress (with the expected output http://www.adress.com/more/adress)
What would be the best way? I was thinking of using regexp and checking
how many ../ preceed the relative URL, then subtracting that amount from the baseurl and adding them to what is left.
8 years later, many browsers (except for Internet Explorer) support the URL constructor (URL(url [, base])).
> new URL('../address', 'http://www.adress.com/more/evenmore/').href
"http://www.adress.com/more/address"
> new URL('../../address', 'http://www.adress.com/more/evenmore/').href
"http://www.adress.com/address"
The following function decomposes the URL then resolves it.
function concatAndResolveUrl(url, concat) {
var url1 = url.split('/');
var url2 = concat.split('/');
var url3 = [ ];
for (var i = 0, l = url1.length; i < l; i ++) {
if (url1[i] == '..') {
url3.pop();
} else if (url1[i] == '.') {
continue;
} else {
url3.push(url1[i]);
}
}
for (var i = 0, l = url2.length; i < l; i ++) {
if (url2[i] == '..') {
url3.pop();
} else if (url2[i] == '.') {
continue;
} else {
url3.push(url2[i]);
}
}
return url3.join('/');
}
Using URI.js (urijs - npm): absoluteTo():
function joinUrl(baseUrl, url) {
var theUrl = new URI(url);
if (theUrl.is("relative")) {
theUrl = theUrl.absoluteTo(baseUrl);
}
return theUrl.toString();
}
The ECMAScript URL Web API mentioned by #ning is a good place to start: especially as it is available in vanilla JS implementations (Node, etc.) and doesn't require you to use a library that does something the implementation nowq already accomplishes. Consulting the MDN documentation, more specifically the examples, is a great place to start.
Borrowing (somewhat) directly from their documentation:
let m = 'https://developer.mozilla.org';
// ... omitted
let d = new URL('/en-US/docs', m);
If you were to do the above, then console.log the .toString of the constructed URL object, your output would be: 'https://developer.mozilla.org/en-US/docs'.
Importantly, if you consult the Syntax section of the documentation, you will note that the second argument is optional and the second argument (as seen in the above example) represents the base URL (though only in the case of two arguments being supplied).
If both argument values are absolute URLs, Web API honors the first and discards the second.
If you are working with Node.js, I would encourage you to look at the native path module for doing work on relative paths, again over using a library. The main motivation here is that spinning up your own algorithm (probably just a call to path here and there) is potentially better than introducing a library that will pull in several other dependencies that may introduce vulnerabilities and unnecessary bloat to your application (or just be too heavy weight for what you need).
However, if you are working on the front end, you won't have path available to you and - as mentioned in #cburgmer's answer comments - Web API's URL doesn't support the relative path case mentioned. In this case, you may need to look for a library to accomplish this for you; however, again, given the other answers, I'd consider trying out a home-spun approach.
To their credit, URI.js currently only integrates one non-dev. dependency and doesn't have a huge footprint.

find words in html page with javascript

how can i search an html page for a word fast?
and how can i get the html tag that the word is in? (so i can work with the entire tag)
To find the element that word exists in, you'd have to traverse the entire tree looking in just the text nodes, applying the same test as above. Once you find the word in a text node, return the parent of that node.
var word = "foo",
queue = [document.body],
curr
;
while (curr = queue.pop()) {
if (!curr.textContent.match(word)) continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE : // 3
if (curr.childNodes[i].textContent.match(word)) {
console.log("Found!");
console.log(curr);
// you might want to end your search here.
}
break;
case Node.ELEMENT_NODE : // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
this works in Firefox, no promises for IE.
What it does is start with the body element and check to see if the word exists inside that element. If it doesn't, then that's it, and the search stops there. If it is in the body element, then it loops through all the immediate children of the body. If it finds a text node, then see if the word is in that text node. If it finds an element, then push that into the queue. Keep on going until you've either found the word or there's no more elements to search.
You can iterate through DOM elements, looking for a substring within them. Neither fast nor elegant, but for small HTML might work well enough.
I'd try something recursive, like: (code not tested)
findText(node, text) {
if(node.childNodes.length==0) {//leaf node
if(node.textContent.indexOf(text)== -1) return [];
return [node];
}
var matchingNodes = new Array();
for(child in node.childNodes) {
matchingNodes.concat(findText(child, text));
}
return matchingNodes;
}
You can try using XPath, it's fast and accurate
http://www.w3schools.com/Xpath/xpath_examples.asp
Also if XPath is a bit more complicated, then you can try any javascript library like jQuery that hides the boilerplate code and makes it easier to express about what you want found.
Also, as from IE8 and the next Firefox 3.5 , there is also Selectors API implemented. All you need to do is use CSS to express what to search for.
You can probably read the body of the document tree and perform simple string tests on it fast enough without having to go far beyond that - it depends a bit on the HTML you are working with, though - how much control do you have over the pages? If you are working within a site you control, you can probably focus your search on the parts of the page likely to be different page from page, if you are working with other people's pages you've got a tougher job on your hands simply because you don't necessarily know what content you need to test against.
Again, if you are going to search the same page multiple times and your data set is large it may be worth creating some kind of index in memory, whereas if you are only going to search for a few words or use smaller documents its probably not worth the time and complexity to build that.
Probably the best thing to do is to get some sample documents that you feel will be representative and just do a whole lot of prototyping based around the approaches people have offered here.
form.addEventListener("submit", (e) => {
e.preventDefault();
var keyword = document.getElementById("search_input");
let words = keyword.value;
var word = words,
queue = [document.body],
curr;
while (curr = queue.pop()) {
if (!curr.textContent.toUpperCase().match(word.toUpperCase())) continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE: // 3
if (curr.childNodes[i].textContent.toUpperCase().match(word.toUpperCase())) {
console.log("Found!");
console.log(curr);
curr.scrollIntoView();
}
break;
case Node.ELEMENT_NODE: // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
});

Categories

Resources