Sending user to their browser's Home Page using Javascript - javascript

Is it possible to get a browser's home page using Javascript?
I'd like to place a link on a page that goes to the home page set in the browser.

EDIT: simplified answer
Identify browsers and:
Call window.home(); for all browsers
Call window.location.href =
"about:home"; for IE
To do so you can use http://jquery.thewikies.com/browser/
The jQuery Browser Plugin is an addon
for jQuery that makes it easy to
uniquely identify your visitors'
browsers.
Other solutions:
<script language="javascript">
function gohome(){
if (typeof window.home == 'function'){ // The rest of the world
window.home();
} else if (document.all) { // For IE
window.location.href = "about:home";
} else {
document.write("<p>Please click on your browser's Home
button.</p>");
}
}
</script>
This is via this website. The poster states that there are issues to target Safari. This can be fixed using this other website.
Using the CSS tricks explained there you can then do:
<script type="text/javascript">
isSafari3 = false;
if(window.devicePixelRatio) isSafari3 = true;
</script>
and use this in the script above to call the correct function:
if (typeof window.home == 'function' || isSafari3)

Default home page (default new tab) URL:
Google Chrome:
https://www.google.com/_/chrome/newtab
Firefox and IE:
about:home
Opera:
opera:speeddial
Safari:
http://livepage.apple.com
To find out the default home page URL of your browser, go to your home page and type location.href in the console. Note that the browser might redirect you to your locale, so you'll need to find out the page before redirection (it happens on Chrome).
If you're using this browser detection code you can use this one-liner to get the correct url:
var homepageurl = browser == 'gc' ? 'https://www.google.com/_/chrome/newtab' : browser == 'op' ? 'about:speeddial' : browser=='sa' ? 'http://livepage.apple.com' : 'about:home'
Browser detection code JSFiddle: https://jsfiddle.net/oriadam/ncb4n882/

Not sure if there is a cross-browser solution. In IE you can use the HomePage behavior and call navigateHomePage.

For FF and the like: window.home();
For IE: location = "about:home";

window.home() didn't work for me in FF37, but this was fine:
location.href = "about:home";

Related

How to detect search provider which has already been added?

I'm trying to build a feature like whenever a user comes to my site, I have added an option to add default search provider in their browser. I have written a code like this for Firefox -
<script>
$(document).ready(function () {
var isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox === false) {
$("#set-susper-default").remove();
$(".input-group-btn").addClass("align-search-btn");
$("#navbar-search").addClass("align-navsearch-btn");
}
if (window.external && window.external.IsSearchProviderInstalled) {
var isInstalled = window.external.IsSearchProviderInstalled("http://susper.com");
if (!isInstalled) {
$("#set-susper-default").show();
}
}
$("#install-susper").on("click", function () {
window.external.AddSearchProvider("http://susper.com/susper.xml");
});
$("#cancel-installation").on("click", function () {
$("#set-susper-default").remove();
});
});
</script>
User clicks on the install button and script runs and the site is added in search provider list. If a user refreshes or again comes to my site, this feature again come. How should I detect it is already added so that whenever a user comes to my site next time it does not appear.
It would be great help if someone can help me out. Thanks :)
Unfortunately you can’t use IsSearchProviderInstalled and AddSearchProvider. They are considered no-ops in Chrome, and should do nothing as HTML Standard describes, more info here: https://www.chromestatus.com/feature/5672001305837568. For now AddSearchProvider works in Firefox, but IsSearchProviderInstalled will return always 0. You can try it by going to https://google.com and adding this code: external.IsSearchProviderInstalled("https://www.google.com"); in the console.
Instead you should try adding search plugin autodiscovery into your webpage. To do so just add the <link> element to the <head>:
<link rel="search"
type="application/opensearchdescription+xml"
title="searchTitle"
href="pluginURL">
More info about it here: https://developer.mozilla.org/en-US/Add-ons/Creating_OpenSearch_plugins_for_Firefox#Autodiscovery_of_search_plugins

I need to prevent the page from displaying until a script is run

I have this script at the very top of my page
<script type = "text/javascript">
if(typeof window.orientation !== 'undefined'){ var ortvalue = "defined"; }
if(ortvalue != "defined") {
document.location.replace("http://www.redirect-here.com");
}
else {
}
</script>
All the script does is check if the user is on a computer, as opposed to a mobile device. If the user is on a computer, then the script redirects to a different site. The script works fine, but sometimes the page loads and displays for a moment before the redirect occurs. It's a minor nuance, but I was hoping there was a way to prevent the page from displaying any content while the redirect occurs.
It takes some time for the redirect to resolve the address if it isn't cached, fetch the content, and display it in the page. This happens asynchronously.
If you can move this script just below the body tag, then you can simply hide the body of the document before the location.replace happens.
<body>
<script>
var ortvalue;
if(typeof window.orientation !== 'undefined') {
var ortvalue = "defined";
}
if(ortvalue !== "defined") {
document.body.style.display = 'none';
document.location.replace("http://www.redirect-here.com");
}
</script>
You said that "the script works fine" otherwise, so I'll not change that, but there may be ways this could fail on newer and newer devices. Here are suggestions of other ways to detect mobile browsers: Detecting a mobile browser
Do following, hide the document, do visibility:hidden and later remove the style tag if it is cell phone or just redirect if not mobile device:
document.write( '<style class="hidedocument" ' +
'type="text/css">body {visibility:hidden;}<\/style>');
<script type = "text/javascript">
if(typeof window.orientation !== 'undefined'){ var ortvalue = "defined"; }
if(ortvalue != "defined") {
document.location.replace("http://www.redirect-here.com");
}
else {
var tempCheck;
var allStyles = document.getElementsByTagName('style');
var i = allStyles.length;
while (i >-1) {
tempCheck = styles[i];
if (tempCheck.className == 'hidedocument') {
tempCheck.parentNode.removeChild(tempCheck);
}
i--;}
}
</script>
The problem is because location.replace is slightly asynchronous wrt the DOM loading/rendering. The JavaScript itself is synchronous and is executed inline with the DOM building. That is, the JavaScript has run even though the page briefly shows the HTML content.
If this is indeed the case one solution within the constraints may be to 'hide' the normal body content (such as setting the body element's display to none) before invoking the location.replace.
<body>
<script>
if (not_on_a_mobile_device) {
document.body.style.display = 'none';
document.location.replace("http://www.redirect-here.com");
}
</script>

Using zxing Barcode Scanner within a web page

Is there a working example how you can use the zxing Barcode Scanner from a web page?
Referring to this documentation:
https://github.com/zxing/zxing/wiki/Scanning-From-Web-Pages
shouldn't the following test code work?
function Test1()
{
$.ajax(
{
url: "zxing://scan/?ret=http%3A%2F%2Ffoo.com%2Fproducts%2F%7BCODE%7D%2Fdescription&SCAN_FORMATS=UPC_A,EAN_13",
success:function()
{
alert("success");
},
error:function()
{
alert("error");
}
});
}
function Test2()
{
$.ajax(
{
url: "http://zxing.appspot.com/scan?ret=http%3A%2F%2Ffoo.com%2Fproducts%2F%7BCODE%7D%2Fdescription&SCAN_FORMATS=UPC_A,EAN_13",
success:function()
{
alert("success");
},
error:function()
{
alert("error");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button1" onClick="Test1();">Test 1</button>
<br>
<br>
<button id="button2" onClick="Test2();">Test 2</button>
I keep getting "error" on my Android 4.4.2 Samsung Galaxy TabPro and Samsung Galaxy S4.
I've tried the stock browser, Chrome, Firefox and Dolphin Browser.
Even http://zxing.appspot.com/scan doesn't work as it always asks me to install the (already installed) app.
Any help would be much appreciated.
ZXing isn't designed to work with AJAX. Instead, it works by opening a parsed URL in the default browser. The behavior of the browser is mainly what's responsible for the user experience from that point forward.
There are several methods posted regarding this; unfortunately, there is no one method that will work for every browser.
Some browsers, when you open them from the command line, will check to see if the URL is already opened in another tab, and if so, will use that tab instead of a new one. This will cause a "onhashchange" event if the zxing link contains "zxing://scan/?ret=mytab.html#{CODE}".
Other browsers don't perform such a check, so we wind up with multiple tabs, all having the same URL (with the exception of the hash), and none of them raising the "hashchanged" event. For those browsers, we need to re-use the page from cache if possible (to prevent network traffic on every scan), and change the localStorage value to what the hash is. If the browser is capable of listening for the "storage" event, we can use that to trigger the code.
The code below works with Chrome, the intrinsic Android browser, and Firefox. It might work with others, but I haven't tried. One Firefox caveat, though, is that the scanner window will only close if the about:config setting "dom.allow_scripts_to_close_windows" is set to "true".
** This was edited to work better with multiple pages that allow scans, and now you can use have different hashes without interfering with the code. **
NEW VERSION 12/19/16
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/javascript">
if(window.location.hash.substr(1,2) == "zx"){
var bc = window.location.hash.substr(3);
localStorage["barcode"] = decodeURI(window.location.hash.substr(3))
window.close();
self.close();
window.location.href = "about:blank";//In case self.close isn't allowed
}
</script>
<SCRIPT type="text/javascript" >
var changingHash = false;
function onbarcode(event){
switch(event.type){
case "hashchange":{
if(changingHash == true){
return;
}
var hash = window.location.hash;
if(hash.substr(0,3) == "#zx"){
hash = window.location.hash.substr(3);
changingHash = true;
window.location.hash = event.oldURL.split("\#")[1] || ""
changingHash = false;
processBarcode(hash);
}
break;
}
case "storage":{
window.focus();
if(event.key == "barcode"){
window.removeEventListener("storage", onbarcode, false);
processBarcode(event.newValue);
}
break;
}
default:{
console.log(event)
break;
}
}
}
window.addEventListener("hashchange", onbarcode, false);
function getScan(){
var href = window.location.href;
var ptr = href.lastIndexOf("#");
if(ptr>0){
href = href.substr(0,ptr);
}
window.addEventListener("storage", onbarcode, false);
setTimeout('window.removeEventListener("storage", onbarcode, false)', 15000);
localStorage.removeItem("barcode");
//window.open (href + "#zx" + new Date().toString());
if(navigator.userAgent.match(/Firefox/i)){
//Used for Firefox. If Chrome uses this, it raises the "hashchanged" event only.
window.location.href = ("zxing://scan/?ret=" + encodeURIComponent(href + "#zx{CODE}"));
}else{
//Used for Chrome. If Firefox uses this, it leaves the scan window open.
window.open ("zxing://scan/?ret=" + encodeURIComponent(href + "#zx{CODE}"));
}
}
function processBarcode(bc){
document.getElementById("scans").innerHTML += "<div>" + bc + "</div>";
//put your code in place of the line above.
}
</SCRIPT>
<META name="viewport" content="width=device-width, initial-scale=1" />
</HEAD>
<BODY>
<INPUT id=barcode type=text >
<INPUT style="width:100px;height:100px" type=button value="Scan" onclick="getScan();">
<div id="scans"></div>
</BODY>
</HTML>
You can make a JS include file for the top block of script, and include it on all the pages where you need scanning capabilities.
Then in the body of your document, you can set an event somewhere to call getZxing(), which will call processBarcode(barcode) that you write into your page. Included is a simple one for example's sake.
Side Note: The first time you run zxing from your page, you'll be asked to choose a default app. Make sure you chose the same browser that you're running the page from. Additionally, if you previously selected a default broswer for zxing and want to change which browser you use for zxing, you'll need to clear defaults from your other browsers.
Many thanks to #sean-owen for his hard work and fantastic product.
UPDATE 12/19/16
Ok, I did a slightly more robust version that works well with Firefox and Chrome. A couple of things I discovered:
Chrome will use the Storage event if the scanner is not set to open Chrome automatically, and will use the Hash event after it becomes default.
Firefox will never use the Hash event, but opens an extra window unless you call the scanner with window.location.href (Thanks, #Roland)
There are a couple of other anomalies, but no deal breakers.
I left the "zx" prefix in the hash, so that the code could delineate between scanner hashes and regular hashes. If you leave it in there, you'll not notice it in the processBarcode function, and non-zx hashes will operate as expected.

Chrome: Force browser refesh?

Developing a Chrome Extension... I'm wondering, can I force the users browser to refresh the current page?
From a background page:
chrome.tabs.getSelected(function(tab){
chrome.tabs.update(tab.id, {url: tab.url});
});
Probably not. If you describe why you need them to refresh perhaps you can find the desired behavior some other way.
Yes, via Javascript (here's an example with a countdown shown on the screen):
var targetURL="http://www.wherever.com/about.php" /* or use about.php */
var countdownfrom=10
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=1){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
window.location=targetURL
return
}
setTimeout("countredirect()",1000)
}

Running a JavaScript code when a browser bookmark is clicked

I've written a code that has successfully created a bookmark for any of the following browsers - IE, Firefox and Opera.
<script language="JavaScript" type="text/javascript">
function bookmark()
{
var title = 'Google';
var url = 'http://google.com';
if (document.all)// Check if the browser is Internet Explorer
window.external.AddFavorite(url, title);
else if (window.sidebar) //If the given browser is Mozilla Firefox
window.sidebar.addPanel(title, url, "");
else if (window.opera && window.print) //If the given browser is Opera
{
var bookmark_element = document.createElement('a');
bookmark_element.setAttribute('href', url);
bookmark_element.setAttribute('title', title);
bookmark_element.setAttribute('rel', 'sidebar');
bookmark_element.click();
}
}
</script>
Now I want my bookmark to run a piece of JavaScript code instead of surfing to Google, when the user clicks on it.
This is called a bookmarklet. You could try replacing 'http://google.com' with "javascript:alert('Annoying message');". However, Firefox at least doesn't allow adding bookmarklets using this API. I suspect IE and Opera may be the same.
You can try putting the js code in an html and then bookmark that html.

Categories

Resources