javascript, simulate keyboard events, work on chrome(webkit) - javascript

in FF, i've used this code:
if (keyCount == lineLimit) {
// method in FF, no Chrome
var mock = document.createEvent("KeyboardEvent"); // or KeysEvent
mock.initKeyEvent("keypress",true,true,null,false,false,false,false,14,0);
var x = document.getElementById('InputCategory');
// rise height before Enter
$(this).height(div_height + font_height + offset_height);
// mock Enter
x.dispatchEvent(mock);
// init keyCount
keyCount = 0;
}
it works, but could not be effective on webkit-based browsers like chrome.
so i asked google and found keyboard event is one of the DOM Level 3 events,here is an aticle: http://www.w3.org/TR/DOM-Level-3-Events/
then i knew /* initKeyboardEvent / is not supported on chrome & safari, / initUIEvent */ i've tried, it didn't work also.
Do virtual keyboard events reall can be simulated on chrome ? plesase help me :)

This works, but it's not generating a keypress-event, rather a text-insert event.
var te = document.createEvent('TextEvent');
te.initTextEvent('textInput', true, true, window, 'test');
<element>.dispatchEvent(te);
That inserts the word 'test' at the end of the input (in your case you'd probably replace that by \n.

Related

Alert when page opened not in Chrome

I'm trying to get an alert to pop up when the user opens my webpage in a browser other than Chrome. I have this:
if (/what to put here to make the below show only if the browser is not Google Chrome?/) {
alert( "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome." );
}
Found this here as a possible condition: navigator.userAgent.search("Chrome"), but can't make it work. Please advise. :-)
As the comments above point out by referencing questions you can test for chrome in the userAgent. But you would want to reverse that:
let notChrome = !/Chrome/.test(navigator.userAgent)
let alertMessage = "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome."
if(notChrome) alert(alertMessage)
This will solve the problem unless the user is spoofing their userAgent. This is unusual though. To fully check you should also check for a feature chrome has AND the userAgent:
let notChrome = !/Chrome/.test(navigator.userAgent) && !("webkitAppearance" in document.body.style)
let alertMessage = "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome."
if(notChrome) alert(alertMessage)
This should to it.
var isChrome = !!window.chrome; // "!!" converts the object to a boolean value
console.log(isChrome); // Just to visualize what's happening
/** Example: User uses Firefox, therefore isChrome is false; alert get's triggered */
if (isChrome !== true) {
alert("Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome.");
}

How to detect IE/Edge using javascript?

I am trying to use javascript to apply a certain style to the pages based on which browser the user is using. I can detect all of the browsers except for IE/Edge. In my code snippet I am just trying to detect IE/Edge and apply the style.
Here is my code:
var bodyStyle = document.querySelector("#bodyArea");
if((navigator.userAgent.indexOf("Edge") != -1 ) || (!!document.documentMode == true ))
{
alert("asdf");
bodyStyle.style.paddingTop = "500px";
}
else
{
bodyStyle.style.paddingTop = "300px";
}
When I put an alert in the else section it gives me an alert, but it doesn't work on the if part. So I think my problem is occurring when I try to detect IE/Edge. Or if it lay elsewhere, let me know. If anyone has any feedback, it will be greatly appreciated. Thanks in advance!
You can use this custom script to detect IE/Edge:
if (/MSIE 10/i.test(navigator.userAgent)) {
// this is internet explorer 10
window.alert('isIE10');
}
if(/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)){
// this is internet explorer 9 and 11
window.location = 'pages/core/ie.htm';
}
if (/Edge\/12./i.test(navigator.userAgent)){
// this is Microsoft Edge
window.alert('Microsoft Edge');
}
Check out this page for the latest IE and Edge user agent strings: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

OpenLayers latitude inaccurately captured in Webkit Mobile browsers

I am programming a page with a Map where I need to capture the location of the Tap/Click on a map and store the coordinates. I am using OpenLayers js. On desktop browsers (IE/FF/Chrome), this is working fine. On mobile devices, the tap is getting captured correctly on the default Android browser (both in real devices and emulators).
However on mobile webkit browsers (iPhone Safari & Android Chrome Beta), we are having a problem where the tap is getting captured for a few pixels higher (towards the north) of the actual tap. The error is not fixed (so, I can't just add 100 to the event's xy to recalibrate the top.)
Here is the code I am using as the clickhandler:
OpenLayers.Control.ClickHandler = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend(
{}, this.defaultHandlerOptions
);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.trigger
}, this.handlerOptions
);
},
trigger: function(e) {
that.inputLonLat_EPSG4326 = null;
var lonlat = that.inputMap.getLonLatFromViewPortPx(e.xy);
that.logMessage("XY " + e.xy);
that.logMessage("LonLoat " + lonlat);
that.inputMarkers.clearMarkers();
that.inputMarkers.addMarker(new OpenLayers.Marker(lonlat,that.icons["green"].clone()));
lonlat.transform(that.inputMap.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
that.inputLonLat_EPSG4326 = lonlat;
// For the moderation sections
$('#alertLatitude').val(that.inputLonLat_EPSG4326.lat);
$('#alertLongitude').val(that.inputLonLat_EPSG4326.lon);
//lonLat2.transform(that.inputMap.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
that.logMessage("Stored lat " + that.inputLonLat_EPSG4326.lat);
that.logMessage("Stored lon " + that.inputLonLat_EPSG4326.lon);
that.callFunction(that.inputMapListener, e);
}
});
Should I be doing anything differently? Has anybody else seen the inaccuracy problem on mobile webkit browsers while using OpenLayers?
I finally found the reason this is happening. It seems that on webkit mobile browsers, the x,y that the library seems to be getting (or deriving) is based on the page and not on the element in which the map is housed. Hence the calculations are off. It seems that the inaccuracy can't be solved by adding the xy of the map element or some such DOM-based figure too (I tried it.)
I solved it by housing the Map in an IFrame and then have the iFrame housed within the map element. This way the x,y as received by the map click handler is accurate within the iFrame and hence the lat, long is also accurate. Since both the parent and iFrame are from the same domain, there are no issues communicating back and forth.
To complete the context, the iFrame based solution is definitely compatible with BB 9 & above, Android Chrome, Android Default and iPhone Safari, as tested by me.
Check out the solution at - http://suat1.vocanic.net//saralee/apps/dengue_alert/ and the iFrame at http://suat1.vocanic.net//saralee/apps/dengue_alert/mobileMap.php (WIP versions liable to change or break with time)

Cannot access document's title element with jQuery (IE 8)

I'm seeing this issue in Internet Explorer 8, but not in Safari or Firefox. So far, I have not tested in other IE versions.
I am developing my own jQuery plugin and, for this question, I've stripped it down to the two relevant lines.
In IE 8, using the code below, $('title').text() does not do anything. docTitle is blank because title is blank, as if the jQuery selector for <title>, $('title') is not working. (Again, AFAIK, this is just in IE 8)
(function ($) {
$.fn.myPlugin = function (options) {
var title = $('title').text(),
docTitle = escape(title);
};
})(jQuery);
http://jsfiddle.net/sparky672/YMBQ2/
However, using the plain JavaScript code below, document.title is working fine in everything including IE 8...
(function ($) {
$.fn.myPlugin = function (options) {
var docTitle = escape(document.title);
};
})(jQuery);
EDIT:
It does not matter that this code is inside a plugin.
Same result in IE 8 with this...
$(document).ready(function () {
var title = $('title').text();
alert(title);
});
Just to clarify, I am not insisting on using this. In fact, I fixed my plugin by simply using document.title instead. If it wasn't clear initially, I'm just asking why this does not work in IE 8.
Can anyone explain why, or what stupid mistake I may have made here?
EDIT 2:
Here are some jQuery Bug reports on this issue
http://bugs.jquery.com/ticket/7025
http://bugs.jquery.com/ticket/5881
http://bugs.jquery.com/ticket/2755
And dozens of others reporting the same thing. The official response is to state, "document.title is the only reliable cross-browser way and should be used instead" and the Ticket is closed. So there you go.
I guess jQuery iterates over all TextNodes and concatenates its nodeValue. IE stores this value differently than other browsers.
var title = document.getElementsByTagName('title')[ 0 ];
title.firstChild // This would be the Text-Object with the characterdata of the title
// Firefox: [object Text]
// IE: null
This should be the reason you cannot get the textContent with jQuery.text(). title.text seems to be cross browser comp. I only tested it in IE 7 and Firefox 3.6 but you can check the other browser if you like. But why not using document.title?
try using $('title').html() which should work in all browsers

What is the correct way to detect Opera using jQuery?

Amazon.com recently updated their javascript, and it's causing problems with some Opera browsers.
Their browser detection code looks like so, but it's faulty:
function sitbReaderIsCompatibleBrowser() {
if (typeof(jQuery) == 'undefined') {
return false;
} else {
var version = jQuery.browser.version || "0";
var splitVersion = version.split('.');
return (
(jQuery.browser.msie && splitVersion[0] >= 6) // IE 6 and higher
|| (jQuery.browser.mozilla && (
(splitVersion[0] == 1 && splitVersion[1] >= 8) // Firefox 2 and higher
|| (splitVersion[0] >= 2)
))
|| (jQuery.browser.safari && splitVersion[0] >= 500) // Safari 5 and higher
|| (jQuery.browser.opera && splitVersion[0] >= 9) // Opera 5 and higher
);
}
}
Nothing obviously wrong jumps out at me with this code, but I've never used jQuery before so I don't know.
Even though this code looks like it's attempting to let Opera users through, when I visit the page with Opera 9.64 I get an "unsupported browser" message. If I change Opera's settings to report itself as Firefox, the page works perfectly! With that in mind, I'm pretty sure it's a problem with the script and not the browser.
Any jQuery experts have a suggestion?
You can replicate the behavior by visiting any book on Amazon and clicking the "look inside this book" link.
Prior to jQuery 1.3, you could use jQuery.browser:
if( $.browser.opera ){
alert( "You're using Opera version "+$.browser.version+"!" );
}
From version 1.3, you should use jQuery.support instead.
Main reason for this is that should should avoid checking for browsers, as features may change from version to version, making your code obsolete in no time.
You should always try to use feature detection instead. This will allow you to see if current browser supports the feature you're trying to use, regardless the browser brand, version, etc.
There is a special window.opera object which is present in all Opera 5+ browsers. So something as simple as:
if (window.opera && window.opera.buildNumber) {
// we are in Opera
}
would be enough.
I check for Opera like this:
if (/Opera/.test (navigator.userAgent)) // do something
Why would you want jQuery?
It is much better to detect javascript capabilities rather than browser userAgent.
ie DOM, XmlHttpRequest, eventing model (event.target vs event.srcElement), ActiveX, Java etc
By focusing on the API functions that you will require, rather than a target browser you will create a more robust set of scripts, and inevitably less special casing.
This link here at opera will probably tell you more
A very simple way from Opera themselves:
if (window.opera) {
//this browser is Opera
}
Source: http://my.opera.com/community/openweb/idopera/
The main reason why Amazon fails on Opera is because the send different code from the server side already... If you visit the same page with Firefox and then save that page and reopen it in Opera it works fine...
But they promised to fix that sometime in January...
I think this way is the best
if ( window.opera.version() == 12) {
}
This example check if opera version is 12. Very useful when I have problems with font-face in Opera.
I don't know for sure ( i never really check for opera anyway) but if the built-in jQuery functionality doesn't detect opera, may be a bug with the jQuery which needs to be fixed. I would suspect if that's the case, it should get resolved fairly quickly.
In current HTML5 times, you can also check for browser features instead often.
if (!window.FormData) { alert("xmlhttprequest L2 FormData interface not available"); }

Categories

Resources