Count visits to various sites in JavaScript - javascript

I am trying to write a Chrome extension that keeps track of how many times one visits a given news site and directs the user to other sites when they've been reading the same one too often. is there a way to do this by looking at the URL on each page load? The pseudocode would be, taking the NY Times as an example:
var nytimesCount = 0;
if (URL includes "nytimes.com")
{
nytimesCount++;
}
Pretty simple. Is there a way to do this? Would using cookies (as per this question: Counting page visits with javascript and cookies), or some other method altogether, be easier?

You can get the URL origin with javascript using window.location.origin, and store your data in an array with the indices being the name of the origin, such as:
if (typeof visitedSites[window.location.origin] !== 'undefined') {
visitedSites[window.location.origin] += 1;
} else {
visitedSites[window.location.origin] = 1;
}
In terms of saving the data, I would look into using HTML5 local storage, which will work great in Chrome. http://diveintohtml5.info/storage.html

Related

JavaScript: Like-Counter with Memory

Complete - Edited Once
I am looking to create a Like Counter with persistent Memory!
Right now, my project is stored on a USB-Drive and I'm not thinking of uploading my semi-finished site to the Internet just yet. I'm carrying it around, plugging and working.
A feature of the site, is a Heart Counter and Like Counter, respective with their symbolic icons.
I have a little sideline JavaScript file that has a dozen functions to handle the click-events and such - such as the Number Count of the counters.
But, as the values of the counters are auto-assigned to Temporary Memory - if you were to reload the page - the counter number would reset to it's default, Zero. A huge headache...
Reading from .txt
I thought of using the experimental ReadFile() object to handle the problem - but I soon found that it needed a user-put file to operate (from my examinations).
Here's my attempt:
if (heartCount || likeCount >= 1) {
var reader = new FileReader();
var readerResults = reader.readAsText(heartsAndLikes.txt);
//return readerResults
alert(readerResults);
}
When loaded, the page runs through standard operations, except for the above.
This, in my opinion, would have been the ideal solution...
Reading from Cookies
Cookies now don't seem like an option as it resides on a per-computer basis.
They are stored on the computer's SSD, not in the JavaScript File... sad...
HTML5 Web Storage
Using the new Web Storage will be of big help, probably. But again, it is on a per-computer basis, no matter how beautiful the system is...
localStorage.heartCount = 0 //Originally...
function heartButtonClicked() {
if (localStorage.heartCount) {
localStorage.heartCount = Number(localStorage.heartCount) + 1
}
document.getElementById('heartCountDisplay').innerHTML = localStorage.heartCount
} //Function is tied to the heartCountButton directly via the 'onclick' method
However, I am questioning whether web storage can be carried over on a USB-Drive...
Summarised ideas
Currently, I am looking to Reading and Editing the files, as it's most ideal to my situation. But...
Which would you use? Would you introduce a new method of things?
Please, tell me about it! :)
if (typeof(Storage) !== "undefined") { //make sure local storage is available
if (!localStorage.heartCount) { //if heartCount is not set then set it to zero
localStorage.heartCount = 0;
}
} else {
alert('Local storage is not available');
}
function heartButtonClicked() {
if (localStorage.heartCount) { //if heartCount exists then increment it by one
localStorage.heartCount++;
}
//display the result
document.getElementById('heartCountDisplay').innerHTML = localStorage.heartCount
}
This will only work on a per computer basis and will not persist on your thumb drive. The only way I can think of to persist the data on your drive is to manually download a JSON or text file.

Refreshing elements inside ul that find place in a iframe

I have a div that contains a iframe from another website. In that website you can find a UL and its updates every time user adds a feedback. This is the ul:
Is it any way I can refresh only this ul every x seconds so I get the feedbacks in realtime?
Thanks
No if they are in a different domains. Using Javascript you can't get information from another website due the Same Origin Police. It's a security restriction that browsers implements and you can't bypass.
Same Origin Police policy permits scripts running on pages originating
from the same site – a combination of scheme, hostname, and port
number – to access each other's DOM with no specific restrictions, but
prevents access to DOM on different sites.
If you want to keep updated from another website you may need use a server side language (JAVA, PHP, NodeJS, etc...) to make a request, parse the return HTML from other website and find the information you need.
EDIT:
If you just need update the iframe every X seconds you can use setInterval:
var refreshFrame= function () {
var iFrames = document.getElementsByClassName("yourClassName");
for(var i = 0; i < iFrames.length; i++) {
if(iFrames[i].className === "yourClassName") {
iFrames[i].src = iFrames[i].src;
}
}
}
window.setInterval(refreshFrame, 3000); // Time in ms
look this FIDDLE

How do you detect and prevent a user from accessing a web app from multiple browser tabs using php/javascript?

I have a web app that I would like to restrict to a single browser tab or window. So the idea is a user logs in and if they open a link in a tab/window or open a new browser tab/window it kills their session. I know many are against this but that's how the app needs to be.
The controller checks if the user is logged in via:
if (!isset($_SESSION['user_logged_in'])) {
Session::destroy();
header('location: '.URL.'login');
}
I have tried setting $_SESSION['user_logged_in'] to false if its true but then obviously you don't go any further than one page.
Is there a way to destroy the session when a new browser tab or window is opened? I'm guessing probably jquery/javascript but not across that side of things.
It's very complex to achieve, unfortunately.
And almost impossible to do it true cross-browser and supported by every browser.
Technically, every new browser tab doesn't differ from the latter, form server's point of view. They share cookies and session too.
The only things that differ is JavaScript session. Say, an example: a site that is fully AJAX-based. First page is always login page. Then everything's changed with AJAX. If you dare to open another tab with this site it will open the first page which is always logging you out be default, for example. This can make it possible, but it's very complex.
New technologies stack like localStorage might make this possible, where you can communicate between tabs sending messages in localStorage. But this isn't fully cross-browser and isn't supported by all browsers versions.
So if you are ok with only limited choice of latest browsers — then dig on localStorage and postMessage.
Just to piggy back on what Oleg said, it would be incredibly difficult since HTTP is stateless and browser tabs share data. One potential way of doing it COULD be on the front end, but a very specific set of circumstances would need to be present and they could easily be bypassed. IF the application is a SPA and the primary body is only loaded once, you could potentially generate a key on the body load and send that with each request. Then, if the body is reloaded (say in a new tab or new window), you could generate a new key which would start a new session.
However, the real question is why you would want to do this. Your user experience will suffer and no real security gains exist.
I have some solution and I want share it with you.
To restrict user to only one tab per session, you may use cookie. I describe here how you may build your webapp in order to archieve that goal.
Each time the web module needs to render the auth/login page, create and store a cookie with a given name. Let's call it browserName. The value of the cookie must be a generated value. You may use java.util.UUID if your programming language is java.
When the browser finished loading your auth/login page, set the browser's name with the generated cookie value. You have to know how to read cookie using JavaScript.
Each time the user load other page than auth/login page, check whether the current browser's name is that one stored in the cookie. If they are differents, prompt user and then you can run a snipt that reset session and redirect to auth/login page.
The following is an example of implementing what I've said.
Snipt to be added in the method that runs before your login page in shown Map<String, Object> v$params = new TreeMap<>();
v$params.put("path", "/");
FacesContext.getCurrentInstance()
.getExternalContext()
.addResponseCookie("browserName", UUID.randomUUID().toString(), v$params);
The mini JavaScript library that help you with cookie and other. Add it globally in your webapp.
/**
* http://stackoverflow.com/questions/5639346/shortest-function-for-reading-a-cookie-in-javascript
*/
(function() {
function readCookie(name, c, C, i) {
if (cookies) {
return cookies[name];
}
c = document.cookie.split('; ');
cookies = {};
for (i = c.length - 1; i >= 0; i--) {
C = c[i].split('=');
cookies[C[0]] = C[1];
}
return cookies[name];
}
window.readCookie = readCookie; // or expose it however you want
})();
// function read_cookie(k,r){return(r=RegExp('(^|;
// )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}
function read_cookie(k) {
return (document.cookie.match('(^|; )' + k + '=([^;]*)') || 0)[2];
}
/**
* To be called in login page only
*/
function setupWebPage(){
window.name = read_cookie("browserName");
}
/**
* To be called in another pages
*/
function checkWebPageSettings(){
var curWinName = window.name;
var setWinName = read_cookie("browserName");
if( curWinName != setWinName){
/**
* You may redirect the user to a proper page telling him that
* your application doesn't support multi tab/window. From this page,
* the user may decide to go back to the previous page ou loggout in
* other to have a new session in the current browser's tab or window
*/
alert('Please go back to your previous page !');
}
}
Add this to your login page <script type="text/javascript">
setupWebPage();
</script>
Add this to your other page template <script type="text/javascript">
checkWebPageSettings();
</script>

Getting Backbutton to work in single page website and implementing "speaking" URLs

I have a single page website and would like to achieve the following:
back button working as if it was a normal website
and instead of say,
www.mysite.com/index.php?p=#this-is-a-great-product
I'd like to have this url
www.mysite.com/this-is-a-great-product
while still having back button working properly.
Regarding 1.) I use the following code ive found which works great:
<!-- Getting BackButton to work properly -->
<script type="text/javascript">
var times = 0;
function doclick() {
times++;
}
function doclick() {
times++;
location.hash = times;
}
window.onhashchange = function() {
if (location.hash.length > 0) {
times = parseInt(location.hash.replace('#',''),10);
} else {
times = 0;
}
}
</script>
…but of course it just changes any anchors to /#1, then /#2 and so forth ro get the backbutton to work. But as I'm not a programmer I don't know how to change it… :(
Regarding 2.) i can add in htaccess this:
>RewriteEngine On
>RewriteRule ^([^/.]+)/?$ /index.php?page=$1
and this changes /index.php?p=products to /products.
So how do I change the above code (under 1.) so it doesn't change all anchors to #1, #2, etc. but instead references / uses the urls I achieved under 2, like
www.mysite.com/this-is-a-great-product
And (probably a very dumb question, but a very important one) -given I use only the new url links on my site- is there any danger that this still might result in duplicate content in any way?
Regarding this, should I (for that reason or any other) sefreferential my single page index.php to itself using rel canonical link=index.php?
Thanks so much in advance!
As mentioned, you will want to use the HTML5 History API. Please note, this API is relatively new and therefore browser support is a concern. At the time of writing, approximately 71% of global Internet users have support for it (see http://caniuse.com/#feat=history for browser support information). Therefore, you will want to ensure you have a fall-back solution for this. You will likely want to use the older #! solution that was popular before the HTML 5 History API was adopted.
If you use the history API to replace, for example, example.com/#!settings with example.com/settings and a user bookmarks that nicer URL, then when they go to visit it, their browser will make a request to the server for /settings (which doesn't actually exist in the web server's context). Therefore, you will need to make sure your web server has some redirection rules (i.e. RewriteEngine) such that it can take the pretty URLs and redirect them to the #! version (and then if the user's browser supports the history API it can replace that with the nice URL).
If you aren't very comfortable programming yourself, I'd recommend using a JavaScript library that does a lot of the work for you. I did some quick searching and discovered the following, though there might be better ones out there: https://github.com/browserstate/history.js
Basically i have created a small prototype on jsfiddle which tracks all the urls accessed via ajax calls.
Also contains navigation to access links back and forth .
How It Actually Works:
I have created a global array called history, which keeps track of all urls accessed via ajax in sequence.
also there a global index defined to keep track of the url being accessed when navigating back and forth the links in history array.
There is History section at the bottom of the jsfiddle, which shows the sequence in which the links are accessed by capturing the link names and posting them in the order in which they were accessed.
JS Code:
$(function () {
var history = [];
var index = 0;
$('.links').on('click', function () {
$('#history').append($(this).text());
var address = $(this).attr('data-ref');
index += 1;
history[index] = address;
$('.links').attr('disabled', 'disabled');
loadExternalPage(address);
console.log('list:' + history);
});
$('#back').on('click', function () {
console.log(index);
index -= 1;
console.log(index);
console.log(history[index]);
loadExternalPage(history[index]);
});
$('#forward').on('click', function () {
console.log(index);
index += 1;
console.log(index);
console.log(history[index]);
loadExternalPage(history[index]);
});
var loadExternalPage = function (address) {
console.log(history[index]);
$('#result-section').load(address, function () {
console.log('data-loaded');
$('.links').removeAttr('disabled');
});
};
});
Live Demo # JSFiddle:http://jsfiddle.net/dreamweiver/dpwmcu0b/8/
Note: This solution is far from being perfect, so dont consider it as final solution but rather use it as a base to build upon
On using BACK and FORWARD functions in the browser top-left button:
In principle, there is no great problem with this as long as you work with the existing storage object (a stack) for previously visited web pages on your browser. This object is the history object and you can see what is in it anytime by right-clicking and selecting "Inspect", then selecting the "Console" tab, then enter window.history and enter.
Check out the Browser Object Model (BOM) section of Pro Java For Web Developers (Frisbee) for the background to the history object. (Just a few pages, an easy read, don't worry.) Just remember that in this process you are storing the new page that you move to, not the old page that you are leaving !
For a simple SPA example, look at this example. codepen.io/tamjk/pen/NWxWOxL
In regard to the URL, the method that the history object uses to load a new page state into the history stack, i.e. pushState(...), has an optional third parameter for associating a dummy URL for each web page that is stored.
Personally, when I first sorted out the BACK & FORWARD functions, I did not use dummy URLs as the browser was being confused by them and I had enough to do sorting out the history sequence using just the first two parameters, i.e.
the state object - a JSON holding enough data to recreate the page stored
a title for the page I expect that you could also use a dummy URL but I will leave that to the student as an exercise, as they say.
But you can add the URL of the new page if you want to.
In the example above, for the state object I just used the IDs of the page's nav link and its content element.
For the title, I programmatically changed the HTML's page title element with each change of page. I did this after noticing that the browser listed the previous pages according to the title element in the HTML code.
Unfortunately, this title does not show up on CodePen when you right-click on the browser BACK and FORWARD buttons due to CodePen's system not allowing it. But it will show on your own sites.
It's important that whatever method you use to store current web page states when using the navbar links to navigate, you DO NOT ADD page states to the browser history when you arrive at them using BACK or FORWARD buttons. Otherwise your history stack will have repetitions of entries going back and deletion of entries going forward.
In the CodePen, this was achieved by having the addToHistory(..) function separate to and outside the scope of the switchPage(...) function. This allows you use of the switchPage function in both normal navbar navigation and browser BACK/FORWARD navigation. The third parameter of switchPage(...) is a boolean indicating if the page is to be stored in history or not.
Anyway, this is just something to get you started.

Cookies to switch links

Situation looks like that:
I need to have button on my site that will link to subpage with video.
There are two subpages - one with high quality video and second with low quality video.
When somebody click on button first time then it redirect him to subpage high quality video. From this subpage he can switch to second subpage (with low quality video).
The problem:
I want to remember in cookies on which web page with video client was last in (low or high quality). So that when client returns to my website, button will lead him to page with video that he was last in.
I use ASP.NET MVC 2. But I think that solution to this problem is probably some javascript.
Any help here much appreciated!
Cookies are passed to the server with each HTTP request.
Assuming your button is generated dynamically on the server, you can inspect the incoming cookies to see if the user has the parameter in question set to low quality and update the button URL accordingly.
ASP docs
From experience with ASP.Net WebForms, its pretty straightforward to access cookies and I am pretty sure things are setup similarly w/ MVC.
String GetBandwidthSetting()
{
HttpCookie bandwidth = Context.Request.Cookies["bandwidth"];
return (bandwidth != null) ? bandwidth.Value : null;
}
String SetBandwidthSetting(String value)
{
HttpCookie bandwidth = new HttpCookie("bandwidth", value);
bandwidth.Expires = DateTime.Now.AddYears(1);
Context.Response.Cookies.Add(bandwidth);
}
You can check this script:
http://javascript.internet.com/cookies/cookie-redirect.html
It is similar to what you need.
In .js you have to change last if statement to one looking similar to that:
if (favorite != null) {
switch (favorite) {
case 'videohq': url = 'url_of_HQ_Video'; // change these!
break;
case 'videolq': url = 'url_of_LQ_Video';
break;
}
And then add this to button/link:
onclick="window.location.href = url"
to your site on which you are redirectiong to those videos.
Remember also to add code that set cookies. You can add action similar to this:
onClick="SetCookie('video', 'videohq' , exp);

Categories

Resources