Read get request parameter with javascript - javascript

I want to create a script that highlights every instance of a string on a page and that string is received as a get request paramater. I want my page to link to the script like: <script src="../Scripts/highlightSearch.js" defer></script> and inside that script I want to have a function like function highlight(content) {...} where content is the string that I want to be highlighted throughout the page. How can I acess content via my script?

In terms of "reading the GET request" there is a relatively new API available that makes reading the querystring parameters trivial. This particular API is URLSearchParams
If you refer to the compatability table at the bottom you'll notice that Internet Exploder does not support this API so, as a possible alternative, you can use quite a simple function to process the querystring yourself. This following function could ( relatively ) easily be modified to provide similar methods to those found in the URLSearchParams api - alternatively search for a Polyfill
const getArgs=function() {
let o={};
location.search.substring(1).split('&').forEach( function( n ){
let l=n.indexOf('=');
if( ~l )o[ n.substring( 0, l ) ]=unescape( n.substring( l + 1 ) );
});
return o;
};
With those in place when you need to read / mainpulate the querystring you can fork the logic
if( 'URLSearchParams' in window ){ /* use methods available to/within the "URLSearchParams" api */ }
else {
let args=getArgs();
let query=args.hasOwnProperty('keyword') ? args.keyword ? false;
if( query ){
let res=RegExp(pattern[, flags]);
/* etc */
}
}
That should, I hope, help give a baseline with which to accomplish the stated goal - there are other ways open to you young Jedi. Good luck.

Related

set page google analytics

I am trying to force the Page Tracking on my site (see: Link). I am using a TMS, but not Google Tag Manager.
What I am hoping to achieve is prepend the market name to the URI which I can pull out of my site's dataLayer (variable = dataLayer.language and thus the new Page Path: dataLayer.language.substring(0,2)+document.location.pathname e.g. /en/pagepath1/pagepath2.
I've created a script below to define this.
There is a small complication here in that some of the pages already have the country/language variation passed in the URL so I have a regular expression to search for the market/language ISO code (lower case) to help perform an if statement that returns document.location.pathname where this is the case.
My script below however, seems to be fine but in testing it is returning "undefined" does anyone why this must be the case?
function PagePath() {
var StandardPagePath = document.location.pathname;
var NewPagePath = dataLayer.language.substring(0, 2) + document.location.pathname;
var LocaleRegExPatt = /^(at|cn|cz|de|dk|en|eu|fr|it|nl|no|pl|pt|pt-br|se)\//
try {
if (StandardPagePath.includes(LocaleRegExPatt)) {
return (StandardPagePath);
} else {
return (NewPagePath)
}
} catch (err) {}
}
My second question is how can I reference this function to pass through to the page tracking i.e. set the page here:
ga('set', 'page', {{PagePath function here}} );
Thanks in advance

How to perform functions on two different domains?

This is the algorithm of what I want to do:
1.Locates flickr links with class' high_res_link and puts them in array [].
2.Opens flickr link with extension "sizes/h/"
3.finds largest photo dimensions on flickr. Then goes to that link. Or if there arent any big enough goes to step 2 and goes to next
array.
4. then opens link to download if downloading is enabled. If not goes to step 2 and goes to next array.
5. Goes to step 2 and goes to next array.
I am trying to write some code that crosses two domains: Tumblr and Flickr.
I have currently written 3 functions with Jquery and Javascript which I want to run on 2 different URLs:
Function #1:
function link_to_flickr() {
var hre = [];
$('.high_res_link').parent(this).each(function(){
var h = $(this).attr('href') +"sizes/o/";
hre.push(h);
});
alert(hre[0]);
}
This finds the links on the Tumblr page to the Flickr pages I want. And puts them in an array.
Function #2:
function find_large_quality() {
var w = 1280;
var h = 720;
var matchingDivs = $("small").each(function () {
var match = /^\((\d+) x (\d+)\)$/.exec($(this).text());
if (match) {
if (parseInt(match[1], 10) >= w && parseInt(match[2], 10) >= h) {
return true;
}
}
return false;
});
var href = $.trim(matchingDivs.text()).match(/\(.*?\)/g);
if (matchingDivs.length >= 1) {
alert("success");
} else {
alert("fail");
}
var ho = $('small:contains("'+href[href.length - 1]+'")').parent(this).find("a").attr("href");
alert("http://www.flickr.com"+ho);
}
This function once on the Flickr URL then searches for an image with dimensions greater than 720p.
Function #3:
function Download(){
var heyho = $('a:contains("Download the")').attr('href');
window.open(heyho, '_blank');
}
This downloads the image file. Once on the Highest quality Flickr URL
Each alert I want to open the URL instead. And perform the next function on. I have been trying for ages and ages of a method to go about doing something like this.
Using AJAX, using PHP, using Jsonp, using jquery.xdomainajax.js, etc... But I can't come up with a sufficient method on my own.
Has anybody got any way they would recommend going about doing something like this?
You usually can't run functions on different domains due to CORS unless the domains allow that.
If you're writing a userscript/extension, what you can do is use postMessage (quick tutorial on how to use it cross-domain) on both pages in a content script and use the achieved inter-page communication to control your script flow.
An alternate method is to use the APIs of the websites you want to access.
Or use Python with BeautifulSoup.

run javascript via url

My Problem is:
I have an eibport:
www.bab-tec.de/
You can See a live demo in the live section.
Now the problem.
I would like to start or run a javascript on this page with entering the url like:
http:// IP-EIBPORT /#javascript:click(Button)
or in another way.
Can someone helps me?
You may want to setup your script to look for a sepcific hash and run a function based on that.
switch(location.hash){
case "#button":
//click button
break;
case "#other":
//do something else
break;
}
Then use urls like /#button or /#other
The way to do exactly what you want is the following, but it's not recommended!
eval(location.hash.substr(1));
Use a url like /#alert('test'); That will work, but it means anyone can link to your site and execute javascript which is a very unsafe thing to do.
You cannot include JavaScript-invoking code in the URL itself. The best you can do is have a script on the destination page that examines the location, and responds accordingly.
As an example, suppose you wanted to expose sum method via the url. If somebody were to load your page with the following query string: ?method=sum&params=5,5, you could have logic in place to look for these parts, and process them.
var methods = {
sum: function () {
var result = 0; i = -1;
while ( ++i < arguments.length )
result += parseInt( arguments[i], 10 );
return result;
}
};
var method = location.search.match(/method=(.*)&/)[1],
params = location.search.match(/params=(.*)$/)[1].split(",");
var result = methods[ method ].apply( this, params );
alert( result );
See it in action: http://jsfiddle.net/jonathansampson/TF5ta/show/?method=sum&params=5,5

Is it possible for the admin to get the full sourcecode of my js-file if I redirect a Javascript file to a local modified Javascript file?

I created a google-chrome-extension which redirects all requests of a javascript-file on a website to a modified version of this file which is on my harddrive.
It works and I do it simplified like this:
... redirectUrl: chrome.extension.getURL("modified.js") ...
Modified.js is the same javascript file except that I modified a line in the code.
I changed something that looks like
var message = mytext.value;
to var message = aes.encrypt(mytext.value,"mysecretkey");
My question is now is it possible for the admin of this website where I redirect the javascript-file to modify his webpage that he can obtain "mysecretkey". (The admin knows how my extension works and which line is modified but doesn't know the used key)
Thanks in advance
Yes, the "admin" can read the source code of your code.
Your method is very insecure. There are two ways to read "mysecretkey".
Let's start with the non-trivial one: Get a reference to the source. Examples, assume that your aes.encrypt method looks like this:
(function() {
var aes = {encrypt: function(val, key) {
if (key.indexOf('whatever')) {/* ... */}
}};
})();
Then it can be compromised using:
(function(indexOf) {
String.prototype.indexOf = function(term) {
if (term !== 'known') (new Image).src = '/report.php?t=' + term;
return indexOf.apply(this, arguments);
};
})(String.prototype.indexOf);
Many prototype methods result in possible leaking, as well as arguments.callee. If the "admin" wants to break your code, he'll surely be able to achieve this.
The other method is much easier to implement:
var x = new XMLHttpRequest();
x.open('GET', '/possiblymodified.js');
x.onload = function() {
console.log(x.responseText); // Full source code here....
};
x.send();
You could replace the XMLHttpRequest method, but at this point, you're just playing the cat and mouse game. Whenever you think that you've secured your code, the other will find a way to break it (for instance, using the first described method).
Since the admin can control any aspect of the site, they could easily modify aes.encrypt to post the second argument to them and then continue as normal. Therefore your secret key would be immediately revealed.
No. The Web administrator would have no way of seeing what you set it to before it could get sent to the server where he could see it.

Google custom search for images only

Since Google image search API is deprecated, one should use Google custom search API for this.
I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'hu'});
google.setOnLoadCallback(function() {
var customSearchOptions = {
enableImageSearch: true,
imageSearchOptions: {
layout: google.search.ImageSearch.LAYOUT_CLASSIC
}
};
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
customSearchControl.setAutoCompletionId('XXX');
customSearchControl.draw('cse', options);
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
The API documentation is quite poor, it only describes how to add additional results.
Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.
searchType = "image"
See this post on the cse blog.
EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.
Per the Google Custom Search Element Control API - documentation web site, this is possible.
https://developers.google.com/custom-search/docs/element
This is the fragment used for searching by image by default:
'defaultToImageSearch'
So I believe the full syntax for using this would be:
<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:
/**
* #param {string} searchTerm - Search term for Google Image search.
* #param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* #param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
function getImageUrl(searchTerm, callback, errorCallback) {
// Google image search - 100 searches per day.
// https://developers.google.com/image-search/
// var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
// '?v=1.0&q=' + encodeURIComponent(searchTerm);
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.image.thumbnailLink;
var width = parseInt(firstResult.image.thumbnailWidth);
var height = parseInt(firstResult.image.thumbnailHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.
I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).
I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.
And yes, it's total BS that Google has provided such lousy support for this API. =)
Try adding this line:
customSearchOptions['disableWebSearch'] = true;
I tried to get a more authoritative answer in the official Google AJAX APIs group,
and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.
check this
Try this one
customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;

Categories

Resources