Changing useragent if ipad - javascript

What I want to do is detect if the user is using an iPad, then change the useragent to iPhone. But I also want to ensure the page detects this change before page load..
I've tried doing this but no luck.
<script type="text/javascript">
var navigator = new Object;
var userAgent = HttpContext.Current.Request.UserAgent.ToLower();
if (userAgent.Contains("ipad;"))
{
navigator.userAgent = 'iPhone';
}
</script>

The userAgent is readonly you can not set it to anything.
You are using HttpContext.Current.Request.UserAgent.ToLower(); which is not valid javascript. This is c# which your browser can not execute.
Instead look at the navigator.userAgent
var nav = '';
if (navigator.userAgent.indexOf('iPad') != -1) {
nav = 'Its an iPad';
} else {
nav = 'Its some other device';
}
console.log(nav);

Related

Safari does not add a break when hitting enter

I want a user to be able to type in a content editable div, hit enter (or come to the end of the line) and have their text collected into a variable and have their cursor put on a new line, standard for any text editor. I have this event listner that checks for those conditions:
writerId.addEventListener('keydown', function(event){
if(event.key === "Enter" || document.getElementById("writer").offsetWidth >= "570") {
if(initialState === true) {
writtingContent = writerId.innerHTML;
blurId.innerHTML = writtingContent ;
writerId.innerHTML = "";
initialState = false;
} else {
writtingContent = writtingContent + writerId.innerHTML;
blurId.innerHTML = writtingContent ;
writerId.innerHTML = "";
}
}
});
The new line works in Chrome, FireFox but not Safari.
Initially I added this as a workaround for Safari:
if(navigator.userAgent.indexOf("Safari") != -1) {
writtingContent = writtingContent + "</br>";
console.log(navigator.userAgent);
}
But it broke things in other browsers (specifically Opera) and I've read that navigator.userAgent is not the best way to go about browser specific issues anyway.
I've seen some workarounds with feature detection but I'm not sure if that's necessary; I'd love if there was an easier way; something, perhaps, I've overlooked.

Can I use javascript timer in a mobile browser

I am using IE in a mobile browser. I add a javascript function to a button that when the User clicks it says 'hello'.
This works.
I then add a timer.
On a desktop browser it works.
it does not work on my mobile browser.
This is my code. (note I Had just tried placing an alert('hi'); in the swapImages() and that did not work either.
var div = document.getElementById('divImage');
var imgCached = document.getElementById('imgCached');
document.execCommand("BackgroundImageCache", false, true);
function OnImgLoaded() {
img1.src = imgCached.src;
}
var interval = 30;
var _timer;
var _index = 0;
function test() {
_timer = setInterval('swapImages()', interval);
}
function swapImages() {
imgCached.onload = OnImgLoaded();
imgCached.src = 'my server url~/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
}
UPDATE!!
I had been runningit on Chrome desktop and not IE. I am mow testing it in IE desktop. I get the same erro so now I can debug.
The error is this line:
img1.src = imgCached.src;
It tells me:
Unable to get property 'src' of undefined or null reference
I have changed the code to:
var imgLive = document.getElementById('imgLive'); (I have renamed the img control)
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
I get the same error.
I look in Source and the control is correctly named..
Thanks
i'm not sure that the following line is valid in your mobile phone:
imgCached.src = 'http://127.0.0.1/Cloud/test/' ...
the timer executes successfully, but the image doesn't get the proper src since the device doesn't run a web server on it (unless you configured one).
and to answer your topic question, yes- you can use javascript timers in mobile browsers just like desktop browsers.
hope that helped.
First of all: Do you ever call the test function, that starts the timer?
Second: Maybe it's really document.execCommand("BackgroundImageCache", false, true), that fails - it may not be enabled in the mobile version of IE that you are using. You can check if it's enabled using the queryCommandEnabled function, see more here: http://msdn.microsoft.com/en-us/library/ie/ms536676(v=vs.85).aspx

Javascript - Changing button image depending on device

I am trying to display the correct button and link depending on what device the user browses to a page on. If android display android app store button if ios display apple store button.
I cannot seem to get it to swap at all even though im making the function default to swap it from android to apple button.
Here is the code:
<html>
<head>
<script type="text/javascript">
var uagent = navigator.userAgent.toLowerCase();
var apple = "/images/ios.jpg";
var android = "/images/android.jpg"
function DetectDevice() {
var but = document.getElementById("AppButton");
if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
toswap.src = apple;
alert("apple");
} else if(useragent.search("android")) {
toswap.src = android;
alert("android");
}
but.src = apple;
}
DetectDevice();
</script>
<title>Device Detection</title>
</head>
<div id="butttons">
<img src="images/android.jpg" name = "AppButton" id="AppButton"/>
</div>
Two issues:
First, your function needs to run after the button has loaded because
document.getElementById("AppButton");
is returning nothing at the moment.
Secondly, you should probably change 2 instances of toswap.src to but.src.
I don't know where var toswap refers to. Try this:
var uagent = navigator.userAgent.toLowerCase();
var apple = "/images/ios.jpg";
var android = "/images/android.jpg"
function DetectDevice() {
var but = document.getElementById("AppButton");
if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
but.src = apple;
alert("apple");
} else if(useragent.search("android")) {
but.src = android;
alert("android");
} else{
but.src = apple; // this is default
}
}
</script>
<div id="butttons">
<img src="images/android.jpg" onload="DetectDevice();" name = "AppButton" id="AppButton"/>
</div>
useragent is not defined either. You may have meant to use uagent which you defined, or you may have meant to rename your variable.

Using a bookmarklet to track a package

I'm trying to write a bookmarklet that tracks a package in the mail. First it checks to see if the tracking page is open, if not it opens it in a new tab, and then sets the value of the form to the tracking number. Finally, it submits the form. What I'm so far unable to do is set the value of the form in the case where the bookmarklet opens up a new tab.
Here's what I have:
javascript: (function(){
var trackingNumber = "/*tracking number*/";
var a = document.forms.trackingForm;
if ('http://fedex.com/Tracking' == document.location) {
trackingForm.trackNbrs.value = trackingNumber;
document.forms.trackingForm.submit();
}
else {
window.open('http://fedex.com/Tracking');
this.window.onload = function(){ //This seems to be the problem
trackingForm.trackNbrs.value = trackingNumber;
onload(document.forms.trackingForm.submit());
}
}
})();
Any ideas?
window.open opens a new window, so if this is going to work at all (I have little experience with bookmarklets), you would have to address the new window directly. Something like this:
else {
new_window = window.open('http://fedex.com/Tracking');
new_window.onload = function(){
new_window.document.trackingForm.trackNbrs.value = trackingNumber;
new_window.document.forms.trackingForm.submit();
// I didn't get at all what the onload() was for, re-add if necessary
}

How do you make a post request into a new browser tab using JavaScript / XUL?

I'm trying to open a new browser tab with the results of a POST request. I'm trying to do so using a function containing the following code:
var windowManager = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interface
s.nsIWindowMediator);
var browserWindow = windowManager.getMostRecentWindow("navigator:browser");
var browser = browserWindow.getBrowser();
if(browser.mCurrentBrowser.currentURI.spec == "about:blank")
browserWindow.loadURI(url, null, postData, false);
else
browser.loadOneTab(url, null, null, postData, false, false);
I'm using a string as url, and JSON data as postData. Is there something I'm doing wrong?
What happens, is a new tab is created, the location shows the URL I want to post to, but the document is blank. The Back, Forward, and Reload buttons are all grayed out on the browser. It seems like it did everything except executed the POST. If I leave the postData parameter off, then it properly runs a GET.
Build identifier: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1
Something which is less Mozilla specific and should work reasonably well with most of the browsers:
Create a hidden form with the fields set up the way you need them
Make sure that the "target" attribute of the form is set to "_BLANK"
Submit the form programatically
The answer to this was found by shog9. The postData parameter needs to be a nsIMIMEInputStream object as detailed in here.
try with addTab instead of loadOneTab, and remove the last parameter.
Check out this page over at the Mozilla Development Center for information on how to open tabs.
You could use this function, for example:
function openAndReuseOneTabPerURL(url) {
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var browserEnumerator = wm.getEnumerator("navigator:browser");
// Check each browser instance for our URL
var found = false;
while (!found && browserEnumerator.hasMoreElements()) {
var browserInstance = browserEnumerator.getNext().getBrowser();
// Check each tab of this browser instance
var numTabs = browserInstance.tabContainer.childNodes.length;
for(var index=0; index<numTabs; index++) {
var currentBrowser = browserInstance.getBrowserAtIndex(index);
if ("about:blank" == currentBrowser.currentURI.spec) {
// The URL is already opened. Select this tab.
browserInstance.selectedTab = browserInstance.tabContainer.childNodes[index];
// Focus *this* browser
browserInstance.focus();
found = true;
break;
}
}
}
// Our URL isn't open. Open it now.
if (!found) {
var recentWindow = wm.getMostRecentWindow("navigator:browser");
if (recentWindow) {
// Use an existing browser window
recentWindow.delayedOpenTab(url, null, null, null, null);
}
else {
// No browser windows are open, so open a new one.
window.open(url);
}
}
}

Categories

Resources