Check if request was blocked by user with javascript - javascript

I'm coding a function to detect if users are using adblockers. When I detect it I send it to Site Catalyst (Omniture).
The problem is: Some adblockers use a black list to block requests and my company catalyst url it's in one of these lists.
When I look in the devtools they block the requests and show a ERR_BLOCKED_BY_CLIENT.
There's a way to check if a request was blocked by client using javascript?

Detecting ad blocker is easy check this answer it might be helpful How to detect ad blocking and show a message
You can check this out it might help
detect-adblocker
Its an implementation of timing answer
Add this before any script in the head tag:
<head>
<title></title>
<meta/>
<!--adBlocker detection code - START-->
<script src="//adblocker.fortiapp.com/ads.js"></script>
<script>
(function (i, o, g, r) {
i[o] = (typeof i[o] == typeof undefined) ? g : r
})(window, 'adblocker', true, false);
</script>
<!--adBlocker detection code - END-->
// Other scripts
</head>
Then later use it:
if (adblocker) {
// the add blocker is enabled
}else{
// ad blocker is not enabled
}

Related

Implementing Google Analytics Script AFTER the Visitor Accept Using Body of Page

The aim is simple, run the google tracking code AFTER the user has accepted and if the user do not accept, do not run.
I went with placing the code inside the tag, but I am struggling to understand how to incorporate a "dismiss" option as well.
This is my "work in progress" code as of right now:
<script>
(function() {
if (!localStorage.getItem('cookieconsent')) {
document.body.innerHTML += '\
<div class="cookieconsent" style="position:fixed;padding:20px;left:0;bottom:0;background-color:#000;color:#FFF;text-align:center;width:100%;z-index:99999;">\
This site uses standard cookies and Google Analytics. By clicking on "I understand", you agree to their use. \
I Understand\
</div>\
';
document.querySelector('.cookieconsent a').onclick = function(e) {
e.preventDefault();
document.querySelector('.cookieconsent').style.display = 'none';
localStorage.setItem('cookieconsent', true);
};
}
})();
</script>
And from what I understand, I need to place the google tracking after this line:
localStorage.setItem('cookieconsent', true);
But since the script tag is already opened, how do I do that?
Example of the tracking code:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXX');
</script>
On top of this, I'm not sure how to add a dismiss option so that the google code does not run. I'm grateful for all the input I can get.
This probably contains the answer to your question Consent Mode (beta):
"Consent Mode (beta) allows you to adjust how your Google tags behave based on the consent status of your users. You can indicate whether consent has been granted for Analytics and Ads cookies. Google's tags will dynamically adapt, only utilizing measurement tools for the specified purposes when consent has been given by the user."

SDK for Facebook playable ads

I want to make HTML playable ad for Facebook platform and show user avatar in it. Is it possible?
According to docs playable ad must not make any HTTP request.
So I just can't make any auth request from playable ad. Seems it does not support Facebook SDK either in this case
Also playable code in the ad must use the JavaScript function FbPlayableAd.onCTAClick() when the viewer interacts chooses the call-to-action.
Is there any reliable documentation for FbPlayableAd methods?
Facebook doesn't appear to offer any helpful information beyond "you need to call the function".
When a playable is served, this <script> is injected into the <head>:
const FbPlayableAd = {
onCTAClick() {
window.parent.postMessage("onCTAClick", "*");
},
};
To get around the missing FBPlayableAd object, solution here was to insert the following <script> after the <body> tag:
<script type="text/javascript">
window.FBPlayableOnCTAClick = () => {
(typeof FbPlayableAd === 'undefined') ?
alert('FBPlayableAd.onCTAClick') : FbPlayableAd.onCTAClick();
}
</script>
And then the CTA button has this onClick:
onClick={() => window.FBPlayableOnCTAClick()}
This allowed us to clear issues with Babel complaining about the missing FbPlayableAd, works fine in test, and functions fine when uploaded to Facebook's Playable Preview tool.

Allowing two sites to communicate to know the current URL of an iframe

I'm trying to figure out a solution to allow an website to know what URL the user is on through an iframe.
Website 1: http://website.website.com (Remote Website, can only add javascript & html to the webpage)
Website 2: https://example.com (Fully Editable, php, html, js.. etc)
Current Code: (Of Website 2 (Example.com)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Website.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body class="body_blank">
<script type="text/javascript">
jq = jQuery.noConflict();
jq(document).ready(function() {
var currentFramePath = '';
var iframe = '<iframe src="{src}" id="#iFrameContainer" style="position:fixed; top:0px; bottom:0px; right:0px; width: 100%; border: none; margin:0; padding:0; overflow: hidden; z-index:999999; height: 100%;">';
var urlFrame = getUrlParameter('currentFrame');
if(urlFrame != null && urlFrame != ''){
console.log("Frame not found");
jq('#iFrameContainer').html(iframe.replace('{src}', urlFrame));
currentFramePath = urlFrame;
}
jq('#iFrameContainer').click(function(){
console.log("Clicked in frame");
currentFramePath = jq(this).attr('href');
console.log(currentFramePath);
});
setInterval(function(){
window.location = window.location.href.split('?')[0] + '?currentFrame=' + currentFramePath;
console.log("Update Query");
}, 5000);
});
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
console.log("Get Query");
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
</script>
<div id="wrapper" class="wrapper_blank">
<iframe src="http://website.website.com" id="#iFrameContainer" style="position:fixed; top:0px; bottom:0px; right:0px; width: 100%; border: none; margin:0; padding:0; overflow: hidden; z-index:999999; height: 100%;">
</div>
</body>
</html>
Problem
If I refresh the page (iframe) on example.com it refreshes and forgets the page that the user is/was on...
As you can see I have attempted to get it working by detecting their page through an iFrame however this is impossible due to it being on a different domain.
Solution?
I'm looking for some sort of solution to do something like described below, bare in mind there could be a better solution.
I want the website website.website.com to get the current path / url of the page the user is on (which is being viewed through an iframe) and for it to send this path/url through to example.com then example.com would update the session / temporary cookie / temporary local storage / variable... etc which would then mean it would adjust the query string to point itself to the correct URL for when the user refreshes their page resulting in the refresh correctly remembering the page they were on.
Attempt
I tried to use the postMessage function by putting the follow code on their respective sites:
Website 1 Extra Code
<script type="text/javascript">
setInterval(function() {
parent.postMessage(window.location.pathname, "https://website.com");
},1000);
</script>
Website 2 Extra Code:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function(e) {
console.log('Parent Message: ', e.data);
}, false);
However nothing happens, no console messages or errors... just nothing.
I've even tried copying the likes of https://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage but nothing in that helped :(
Any ideas what I am doing wrong and a way to resolve it to achieve this?
Thanks
Edits
I've tried the following js inside http://website.website.com but it didn't work:
localStorage.setItem('CurrentURLChecker', window.location.href)
if (localStorage.getItem('CurrentURLChecker')) {
if (window.parent.location.href == "https://website.com/" ) {
console.log("URL FOUND");
}
}
Uncaught DOMException: Blocked a frame with origin "http://website.website.com" from accessing a cross-origin frame at http://website.website.com/:251:44
EDIT - An example
Website 1 = "http://stackoverflow.serviceprovider.com"
Website 2 = "https://stackoverflow.com"
Website 2 contains an iframe which shows the exactly what Website 1 shows.
I am never going to visit Website 1, all clicks are done on Website 2
If I was to click on a link inside the iframe and it was to navigate to: http://stackoverflow.serviceprovider.com/this-new-page/ then Website 1 should be able to detect this and store the iframes location and remember it.
Now if I refresh my browser instead of the iframe loading http://stackoverflow.serviceprovider.com it would instead load the page they actually refreshed which is http://stackoverflow.serviceprovider.com/this-new-page/
The tab/window URL will always stay on https://stackoverflow.com/ but it would be a necessity to append a query string so the links can be made sharable.
It's that simple.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain.
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
Since you can add javascript to the website 1 (http://website.website.com) you could create a session with javascript and save the current page the user visits in the cookies (as described here). When the user visits the home page of website on (which is happening, when the user reloads the website 2) you could get this value with javascript and load the saved page (window.location.href = 'http://website.website.com/YourSavedPage').
If you don't want that redirection every time the user visits the home page of website 1, you could think about creating a own page to redirect the user to the last opened page and to open that page once, when the iframe is loaded.
It seems like the targetOrigin (second argument of postMessage) may simply not match. Do not forget that the protocol, host & port must all be an exact match.
From the markup you posted, the iframe src domain is http://website.website.com while the parent domain is https://example.com.
If you wish for http://website.website.com to communicate it's URL to https://example.com then posting a message from the iframe should read:
window.parent.postMessage(window.location.pathname, 'https://example.com');
To make sure that the targetOrigin filter is not what's causing communication issues you can also use * for testing.
It seems that you are doing the opposite in your example (passing source domain instead of target domain) and it's also very misleading that you use "website 1" to reference the embedded site and "website 2" to reference the parent site in your explanation: I would expect the opposite.
The code samples with http://website.website.com and https://example.com doesn't work because there are on different URI schemes. One is http and another is https.
So, they have to be on the same HTTP protocol for this to work(either both http or both https).
In my example, I am using parent window URL as https://parent.example.com and iframe URL as https://child.somesite.com.
In iframe Site Code:
When the iframe site loads, we are going to send a postMessage() to the parent site about the current URL by assigning event listeners using addEventListenerto anchor tags, whenever they are clicked.
So, when an anchor tag is clicked, we prevent the default flow of route, send a message about current URL to the parent window and set current window href to the anchor's href.
Code:
var a_tags = document.getElementsByTagName('a');
for(var i=0;i<a_tags.length;++i){
a_tags[i].addEventListener('click',function(event){
event.preventDefault();
var current_href = this.getAttribute('href');
var new_location = current_href.match(/^http(s)?:\/\/.+$/) !== null ? current_href : window.location.origin + current_href;// be careful about leading '/' when dealing with relative URLs.
window.parent.postMessage(new_location,'https://parent.example.com');
window.location.href = new_location;
});
}
In parent window code:
Here, we will just attach an event listener to message event and check if the event was fired from our child site itself using the referrer present in event.origin.
If it's not, we return. If it is, we update our localStorage and set the URL received to the iframe_url key.
While refreshing the page, we first check if localStorage has this key set or not. If not, we load iframe as is, else, we load the URL we have in our storage by setting it's src attribute.
Note that we make an iframe element from javascript to avoid attaching separate event handlers to deal with it's src when requested on a new tab in the window.
Code:
const IFRAME_SITE_DOMAIN = 'https://child.somesite.com';
window.addEventListener('message',function(event){
if(event.origin !== IFRAME_SITE_DOMAIN) return;
localStorage.setItem('iframe_url',event.data);
});
var iframe = document.createElement('iframe');
if(localStorage.getItem('iframe_url') === null){
iframe.setAttribute('src',IFRAME_SITE_DOMAIN);
}else{
iframe.setAttribute('src',localStorage.getItem('iframe_url'));
}
iframe.setAttribute('height','500');
iframe.setAttribute('width','500');
document.body.append(iframe);
Sharable Links:
We make a button and span for sharable user actions like so.
Code:
<button id='share_resource_state'>Share Link</button>
<span id='share_url'></span>
Now, we add the iframe's current URL in URL fragments(characters after #). Since we are adding this in a fragment, we need not worry about it's effect on server side of parent site as it is never sent to the server and plays a role purely on the client's browser.
We convert the iframe's URL to base64 using btoa() while sharing and decode it using atob() when requested on a new tab or window.
This changes the current code on parent site(main window) a bit like so.
Code:
const IFRAME_SITE_DOMAIN = 'https://child.somesite.com';
window.addEventListener('message',function(event){
if(event.origin !== IFRAME_SITE_DOMAIN) return;
localStorage.setItem('iframe_url',event.data);
});
var iframe = document.createElement('iframe');
if(localStorage.getItem('iframe_url') === null){
if(window.location.hash != ''){
try{
var decoded_string = atob(window.location.hash.substring(1));// to remove the # from the fragment and get the base64 encoded data.
if(decoded_string.indexOf('iframe_url=') !== -1){
iframe.setAttribute('src',decoded_string.split('=')[1]);// we split the string based on '=' and assign the iframe URL which was set at the time of sharing
}else{
iframe.setAttribute('src',IFRAME_SITE_DOMAIN); // we don't deal with the fragment at all since it isn't encoded for our iframe purpose.
}
}catch(e){
iframe.setAttribute('src',IFRAME_SITE_DOMAIN); // we don't deal with the fragment at all.
}
}else{
iframe.setAttribute('src',IFRAME_SITE_DOMAIN); // we set URL as is.
}
}else{
iframe.setAttribute('src',localStorage.getItem('iframe_url'));
}
iframe.setAttribute('height','500');
iframe.setAttribute('width','500');
document.body.append(iframe);
document.getElementById('share_resource_state').addEventListener('click',function(){
var iframe_sharable_url = localStorage.getItem('iframe_url') === null ? IFRAME_SITE_DOMAIN : localStorage.getItem('iframe_url');
document.getElementById('share_url').innerHTML = window.location.href.split('#')[0] + '#' + btoa('iframe_url=' + iframe_sharable_url);
});
Some pointers before we start, whenever you have a problem it is always good to check the following basics first.
Basic problem solving
Make a bare minimum proof of concept that only shows the problem and nothing else. Remove all extra markup, styling and code.
Make sure your libraries are up to date (you are using jquery 1.11.3 instead of 3.3.1).
Follow standards, conventions, best practices if you are swimming upstream you only make it harder on yourself.
Best practices used in this answer
You are advised to follow these, they are called best practices because they make life easier not harder.
script tags go at the bottom of the page
encapsulate all your own scripts with a self executing function block in order not to pollute the global namespace
using the popular and well known $ as the jQuery reference so that everyone understands each other
using use strict javascript directive will warn about problem areas in advance
terminology
parent - refers to the main document in the browser window with the iframe markup
child - refers to the document inside the parent's iframe
Cross frame access - the answer
Access child document from the parent document
To access the child document from the parent iframe we use iframe.contentWindow. Once we have the iframe window we gain access to the child document with iframe.contentWindow.document
Access parent document from the child document
To access the parent iframe from the child document we use window.frameElement. Once we have the parent iframe element we can access the parent document with window.frameElement.ownerDocument.
The basic example
Unfortunately your examples are so convoluted with numerous problems outside the scope of this question that I was compelled to re-create these pages in order to facilitate as examples.
These examples show retrieving both the child and parent location from either the child or the parent and visa versa.
The Parent - test.html
Notice the span ids parentOut and childOut which gets populated with jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Website.com</title>
</head>
<body>
<h1>Parent page</h1>
<span>Parent location: <span id="parentOut"></span></span><br>
<span>Child location: <span id="childOut"></span></span><br>
<div id="wrapper">
<iframe src="test_child.html" id="#iFrameContainer" width="100%" height="300"></iframe>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
// script encapsulation
(function ($) { "use strict";
// jQuery ready
$(function() {
$('#parentOut').text(document.location);
$('#childOut').text($('iframe')[0].contentWindow.document.location);
// the iframe by tag name
console.log($('iframe')[0]);
// the iframe by id
console.log($('#iFrameContainer')[0]);
// the iframe window
console.log($('iframe')[0].contentWindow);
// the child document
console.log($('iframe')[0].contentWindow.document);
});
})(jQuery);
</script>
</body>
</html>
The Child - test_child.html
Notice the span ids parentOut and childOut which gets populated with jQuery. There are also several hyperlinks of pages that WON'T work, see topic Security policies.
<!DOCTYPE html>
<html>
<head>
<title>Website.com</title>
</head>
<body>
<h1>Child page</h1>
<span>Child location: <span id="childOut"></span></span><br>
<span>Parent location: <span id="parentOut"></span></span><br>
<h3>Some child pages that DON'T work</h3>
SecurityError: Protocols, domains, and ports must match.<br>
SecurityError: Protocols must match.<br>
X-Frame-Options SAMEORIGIN<br>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
// script encapsulation
(function ($) { "use strict";
// jQuery ready
$(function() {
$('#childOut').text(document.location);
$('#parentOut').text(window.frameElement.ownerDocument.location);
// parent iframe
console.log(window.frameElement);
// parent document
console.log(window.frameElement.ownerDocument);
});
})(jQuery);
</script>
</body>
</html>
Being notified of child location changes
To be notified of location changes on the child document we can use the events onload or onloadstart to notify the parent.
$(document).on('load' function (event) {
$(window.frameElement.ownerDocument).append($('<p>').text('The location changed to:'+this.location);
});
Security policies
As we can see this functionality is quite powerful as it completely exposes both the parent and child documents to each other and visa versa. Because this allows you access to manipulate the content there are security policies in place to prevent us from manipulating the integrity of content that we do not own.
Protocols, domains, and ports must match
There is slightly different wording for similar errors but they all boil down to the child page must have the same domain name, same port and use the same protocol as the parent or access is blocked. The first two examples on the child page will return these errors respectively.
SecurityError: Blocked a frame with origin "http://127.0.0.1:1221" from accessing a frame with origin "http://my.umt.edu". Protocols, domains, and ports must match.
SecurityError: Blocked a frame with origin "http://127.0.0.1:1221" from accessing a frame with origin "https://en.wikipedia.org". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
These pages are allowed to be viewed in an iframe but if and only if the children are located at http://127.0.0.1:1221 (in my case) will this functionality be allowed.
Even further security
We can also completely prevent our sites from being viewed in an iframe. By means of the X-Frame-Options http response header, if configured with SAMEORIGIN the browser will refuse the page from being loaded in the frame. See last example on child page.
Conclusion
It is much simpler to find out exactly what the problem is if we set our project aside and start again with only the problem pieces. This also makes it much easier for someone to assist and provide a useful answer.
From what I understand of your use case, what you want to do is not allowed. You can freely make use of frames on your own site with your own pages but it is not allowed to manipulate someone else's content.
nJoy!
Just a though, based on the assumption that you can access and edit to the second website yet the server does not support PHP or any other programming/scripting language and you're stuck with HTML and Javascript:
In the parent PHP page which you are embedding the iframe into, you could call the iframe with an added parameter as shown bellow:
<iframe src="http://website.website.com/example.html?parent=<?=$_SERVER['HTTP_REFERER'];?>"></iframe>
Then in the child html page you can catch the parameter passed with the GET method with JavaScript or jQuery and use it for your purpose of determining the page, as bellow:
<script>
$(document).ready(function(){
var urlParams = new URLSearchParams(window.location.search);
var parentPage = urlParams.get('parent'); //which will store "https://example.com" in the variable. Now that you have the parent page URL you can manipulate it.
});
</script>
Even if you can't edit the html, you can inject JavaScript and HTML to the DOM of the iframe page through parent page and have it immediately run by declaring it within a jQuery function like so:
(function() {
var urlParams = new URLSearchParams(window.location.search);
var parentPage = urlParams.get('parent');
})();
I hope this made at least a little bit of sense, and can be helpful in any way. Good luck with your quest.
Cheers!
1, you need iframe show the same url even after reload
2, iframe and parent cross origin
3, you can inject js in iframe pages
4, parent page fully in control
check out https://github.com/postor/iframe-url-remember
npm i && npm run start and visit http://localhost:3000
postMessage works, I will explain in detail later, I have to catch a bus
I use node to serve static and mimic cross origin, so you can use nginx apache or php serve to host the public folder, and use lan IP and localhost mimic cross origin, you may need to modify some src
public/js/index.js is for parent page
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
console.log(event)
localStorage.setItem('iframesrc', event.data)
}
var src = localStorage.getItem('iframesrc')
src && (document.getElementById('iframe').src = src)
1.listen to message event, whenever new url comes write it into localStorage
2.on page load, read url from localStorage and modify src of iframe
public/js/iframe.js for the pages inside iframe
window.parent.postMessage(location.href, '*');
1.on page load, send url to parent page
it's easy and working
you can use cookie instead of localstorage then you can use php update iframe src before sending to client browser
or php session, you may need to trigger an ajax to notify server whenever url change
You could use a tracking pixel and pass the current path of the iframe as parameter:
var pathname = window.location.pathname;
var d = new Date();
var imageUrl = 'http://www.example.com/trackingpixel.php?path='
+ pathname + '&time=' + d.getTime();
var img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img);
And in the parent domain, create the route trackingpixel.php and save the current path in the session:
if( !isset($_SESSION['time']) || ($_GET['time'] > $_SESSION['time'])) {
$_SESSION['time'] = $_GET['time'];
$_SESSION['path'] = $_GET['path'];
}
Then when you reload the page, you can get the path from the session:
if(isset($_SESSION['path'])) {
$iframeUrl = $_SESSION['path'];
}
else {
$iframeUrl = 'http://website.website.com';
}
Note that these is a slight chance this is not going to work if the reload is executed before the tracking pixel from the previous load.
PS: Nowadays ad block extensions are quite popular and they may prevent the pixel from "firing up", I would advice to test whether the pixel works with some of the popular extensions.

JavaScript - How to know if web-page load for the first time, or after a refresh?

I would like to execute a JavaScript function after a web-page was refreshed (any way: F5 key, browser's refresh key, user re-enter same URL or any other method).
This method should be execute only after refresh, not after 1st page-load.
Something like:
window.onrefresh = function() { ... }; // of curse, onrefresh isn't real event
I find some solutions in the web, but none meat my needs:
Dirty Flag
This method is simple, on load check flag - if flag not exist this is first load, else set the flag:
Save flag in local-storage/cookie. The flag can be current Date/Time.
If on-load flag not exist create it - this is first load. Else if flag exist compare it to current Date/Time - after refresh.
Save the flag in the site URL. The flag will be '#' sign ('#' - will not change the site Navigation). Same as before on-load test if '#' exist at the end of the URL this is "refresh" load, else this is a first load - we need to add a '#' at the end of the URL.
performance.navigation
The window object has this property: window.performance.navigation.type which can have 3 values:
0 - Page loaded due to link
1 - Page Reloaded
2 - Page loaded due to Back button
However this not working as expected. This value is always "1", on both first load and after refresh.
You can use the Navigation Timing API to gather performance data on the client side which you can then transmit to a server using XMLHttpRequest or other techniques. A Performance object offers access to the performance and timing-related information from the browser.
We can do so by using Navigation Timing API. The main interface of Navigation Timing API for your requirement is performance.navigation.type which checks the URL loaded in browser for the first time or it is loaded. Here is the sample.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
if (window.performance) {
alert("Browser Supports");
}
if (performance.navigation.type == 1) {
alert("Reloaded");
} else {
alert("Not Reloaded");
}
</script>
</head>
<body>
<h2>testing</h2>
</body>
</html>
Hope it helps you

Is there any way to count number of tabs are opened in chrome?

I am trying to find a way to count a number of tabs that are currently open in Chrome by javascript.
I have searched and found chrome.tabs.query(). But when I opened my console and tried it I got an undefined message.
Is it not supported anymore by Chrome, or can it only be used in extension development?
As wscourge has implied, chrome.tabs.query() is a Chrome extension API, which is only available to extensions, not web page JavaScript. In fact, it is only available in the background context of an extension (i.e. not content scripts).
To find the number of tabs that are open, you could do something like:
chrome.tabs.query({windowType:'normal'}, function(tabs) {
console.log('Number of open tabs in all normal browser windows:',tabs.length);
});
If you want to run this from a console, you will need to have an extension loaded that has a background page. You will then need to open the console for the background page. From that console, you can execute the above code.
I found the answer to this question here: https://superuser.com/questions/967064/how-to-get-tab-count-in-chrome-desktop-without-app-extension
Go to chrome://inspect/#pages
Run the following line of code in the javascript console:
document.getElementById("pages-list").childElementCount
The tabs count will be printed to the console.
Local and Session storage
In case when we want count only tabs witch our website - first on page load (open tab) event we generate tab hash and we save it in sessionStorage (not shared between tabs) and as key in TabsOpen object in localStorage (which is shared between tabs). Then in event page unload (close tab) we remove current tab hash (saved in sesionStorage) from TabsOpen in localStorage.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My project</title>
...
<script>
function tabLoadEventHandler() {
let hash = 'tab_' + +new Date();
sessionStorage.setItem('TabHash',hash);
let tabs = JSON.parse(localStorage.getItem('TabsOpen')||'{}');
tabs[hash]=true;
localStorage.setItem('TabsOpen',JSON.stringify(tabs));
}
function tabUnloadEventHandler() {
let hash= sessionStorage.getItem('TabHash');
let tabs = JSON.parse(localStorage.getItem('TabsOpen')||'{}');
delete tabs[hash];
localStorage.setItem('TabsOpen',JSON.stringify(tabs));
}
</script>
...
</head>
<body onunload="tabUnloadEventHandler()" onload="tabLoadEventHandler()">
...
</body>
</html>
Thanks to this in TabsOpen object in localStorage we have information about current open tabs which can be read by
let tabsCount = Object.keys( JSON.parse(localStorage.getItem('TabsOpen')||'{}') ).length
It can only be used in extension development.
You are not able to access that information from document level.
This is not a solution using javascript, but maybe it can help double-check the count against another solution. It is by far the easiest (one-click) solution that works for me:
If you have chrome sync enabled, simply navigate to chrome.google.com/sync
It should give you the count of open tabs, among other counts (e.g. bookmarks, extensions, etc)

Categories