Running a JavaScript code when a browser bookmark is clicked - javascript

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.

Related

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.

Render an iFrame dynamically in Firefox

I generate an iFrame dynamically like this
var iframe=document.createElement('iframe');
document.body.appendChild(iframe);
var iframedoc=iframe.contentDocument||iframe.contentWindow.document;
iframedoc.body.innerHTML="HI";
Fiddle: http://jsfiddle.net/Pbj7S/
It works in Google Chrome, Opera, Safari, but not in Firefox.
Any idea why?
This works :
var iframe=document.createElement('iframe');
document.body.appendChild(iframe);
setTimeout(function(){
var iframedoc=iframe.contentDocument||iframe.contentWindow.document;
iframedoc.body.innerHTML="HI";
}, 10);
The problem was that you were trying to access the iframe document before it was available in the DOM.
The delay isn't important, the important point is that browsers update the display (and some js accessible objects in the case of Firefox) only after the js thread has finished working.
Nothing like that is necessary. You do not need to use timeout or anything for firefox to behave like chrome. In your code just set the source to 'javascript:' would do it. Example bellow:
iframe.src = 'javascript:';
or just use:
iframe.src = 'about:';
don't set with blank. Will work just fine in firefox, chrome, opera, etc....

javascript not working in firefox

I have a master page which is having Javascript code which looks like this:
<script type="text/javascript">
function ClientPrint(str)
{
alert('before');
PrintControl.RawPrint(str);
alert('after');
}
</script>
And the child form is calling this Javascript by the code
Page.ClientScript.RegisterStartupScript(Me.GetType, "jcr", "ClientPrint('" & StrFinalBill & "')", True)
This code is working absolutely fine in IE but not in anyother browser in Firefox error console I’m getting this error “printcontrol is not defined”.
Can anyone please help me?
IE supports refering to a node via its id. for firefox and other browsers use -
function ClientPrint(str)
{
alert('before');
var PrintControl = document.getElementById(controlId);
PrintControl.RawPrint(str);
alert('after');
}

Cross-browser bookmark/add to favorites JavaScript [duplicate]

This question already has answers here:
How do I add an "Add to Favorites" button or link on my website?
(5 answers)
Closed 9 years ago.
Is there any cross-browser bookmark/add to favorites using JavaScript.
Searched for some list but none is working. Can you please suggest any?
jQuery Version
JavaScript (modified from a script I found on someone's site - I just can't find the site again, so I can't give the person credit):
$(document).ready(function() {
$("#bookmarkme").click(function() {
if (window.sidebar) { // Mozilla Firefox Bookmark
window.sidebar.addPanel(location.href,document.title,"");
} else if(window.external) { // IE Favorite
window.external.AddFavorite(location.href,document.title); }
else if(window.opera && window.print) { // Opera Hotlist
this.title=document.title;
return true;
}
});
});
HTML:
<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
IE will show an error if you don't run it off a server (it doesn't allow JavaScript bookmarks via JavaScript when viewing it as a file://...).
function bookmark(title, url) {
if (window.sidebar) {
// Firefox
window.sidebar.addPanel(title, url, '');
}
else if (window.opera && window.print)
{
// Opera
var elem = document.createElement('a');
elem.setAttribute('href', url);
elem.setAttribute('title', title);
elem.setAttribute('rel', 'sidebar');
elem.click(); //this.title=document.title;
}
else if (document.all)
{
// ie
window.external.AddFavorite(url, title);
}
}
I used this & works great in IE, FF, Netscape.
Chrome, Opera and safari do not support it!
How about using a drop-in solution like ShareThis or AddThis? They have similar functionality, so it's quite possible they already solved the problem.
AddThis's code has a huge if/else browser version fork for saving favorites, though, with most branches ending in prompting the user to manually add the favorite themselves, so I am thinking that no such pure JavaScript implementation exists.
Otherwise, if you only need to support IE and Firefox, you have IE's window.externalAddFavorite( ) and Mozilla's window.sidebar.addPanel( ).

Sending user to their browser's Home Page using 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";

Categories

Resources