Problem with Google Chrome and Javascript. Guru needed! - javascript

i have a strange problem only in Chrome using an iframe but working in all others common browser.
the problem: If i type in the IFRAME and then press the button to send, it work fine, the focus back to the IFRAME and the cursor BLINK.
But if i type and then press ENTER to invoke the event handler function, the focus back but the cursor disappear. And then if you go in another window and then back the cursor appear. This happen only in Chrome. I did the example page to show the problem in action. Click the link below to see.
UPDATE: I added the code also here below
var editorFrame = 'myEditor'
function addFrame() {
var newFrame = new Element('iframe', {
width: '520',
height: '100',
id: editorFrame,
name: editorFrame,
src: 'blank.asp',
class: 'myClass'
});
$('myArea').appendChild(newFrame);
window.iframeLoaded = function() {
// this is call-back from the iframe to be sure that is loaded, so can safety attach the event handler
var iframeDoc, UNDEF = "undefined";
if (typeof newFrame.contentDocument != UNDEF) {
iframeDoc = newFrame.contentDocument;
} else if (typeof newFrame.contentWindow != UNDEF) {
iframeDoc = newFrame.contentWindow.document;
}
if (typeof iframeDoc.addEventListener != UNDEF) {
iframeDoc.addEventListener('keydown', keyHandler, false);
} else if (typeof iframeDoc.attachEvent != UNDEF) {
iframeDoc.attachEvent('onkeydown', keyHandler);
}
};
}
function resetContent()
{
var myIFrame = $(editorFrame);
if (myIFrame) myIFrame.contentWindow.document.body.innerHTML='';
}
function setEditFocus()
{
var iFrame = document.frames ? document.frames[editorFrame] : $(editorFrame);
var ifWin = iFrame .contentWindow || iFrame;
ifWin.focus();
}
function send()
{
resetContent();
setEditFocus();
}
function keyHandler (evt) {
var myKey=(evt.which || evt.charCode || evt.keyCode)
if (myKey==13) {
if (!evt) var evt = window.event;
evt.returnValue = false;
if (Prototype.Browser.IE) evt.keyCode = 0;
evt.cancelBubble = true;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.preventDefault) evt.preventDefault();
send();
}
}
In the HTML page
<body onload="addFrame()">
<div id="myArea"></div>
<input id="myButton" type="button" value="click me to send [case 1]" onclick="send()">
To make more easy to understand the problem i've create a specific page to reproduce the problem with full example and source included.
You can view here by using Google Chrome:
example of the problem
I really need your help because i tried to solve this problem for many days with no luck. And all the suggestions, tips and workaround are well accepted.
Thanks in advance.

I'm not really sure what the cause of the issue is, as there are times where Chrome will give focus to the element correctly, though most of the time it does not. You shouldn't need to request focus at all, since the focus is not lost when you press the key. If you omit the setEditFocus() call, you should notice that it still works correctly in everything but Chrome, which apparently gets offended that you've removed all of the content in the body.
When you set contenteditable, every browser sets the innerHTML of the iframe document's body element to be something different:
Browser | innerHTML
-----------------------------
Internet Explorer | ''
Opera | '<br>\n'
Firefox | '<br>'
Chrome/Safari | '\n'
If you're not expecting to see that extra stuff when you parse the content later, you might want to remove it upfront in addFrame().
I was able to "fix" the problem by doing the following:
First, update the event handler so we can return false in it and prevent Opera from generating HTML for fun when we call getSelection() later...
function addFrame() {
...
window.iframeloaded = function() {
...
if (typeof iframeDoc.addEventListener != UNDEF) {
iframeDoc.addEventListener('keypress', keyHandler, false);
} else if (typeof iframeDoc.attachEvent != UNDEF) {
iframeDoc.attachEvent('onkeypress', keyHandler);
}
}
}
Edit: Removed original function in favour of the new one included below
Finally, return false from the key press handler to fix the Opera issue mentioned above.
function keyHandler (evt) {
var myKey=(evt.which || evt.charCode || evt.keyCode)
if (myKey==13) {
...
return false;
}
}
I had originally done what syockit suggested, but I found it was doing weird things with the caret size in Chrome, which this method seems to avoid (although Firefox is still a bit off...). If you don't care about that, setting the innerHTML to be non-blank is likely an easier solution.
Also note that you should be using className instead of class in the object you pass to new Element(), since IE seems to consider it a reserved word and says that it's a syntax error.
Edit: After playing around with it, the following function seems to work reliably in IE8/Firefox/Chrome/Safari/Opera for your more advanced test case. Unfortunately, I did have to include Prototype's browser detection to account for Opera, since while everything looks the same as far as the JavaScript is concerned, the actual behaviour requires different code that conflicts with the other browsers, and I wasn't able to find a better way to differentiate between them.
Here's the new function, which focuses on the editable content of the iframe, and makes sure that if there is already content in there, that the caret is moved to the end of that content:
function focusEditableFrame(frame) {
if (!frame)
return;
if (frame.contentWindow)
frame = frame.contentWindow;
if (!Prototype.Browser.Opera) {
frame.focus();
if (frame.getSelection) {
if (frame.document.body.innerHTML == '')
frame.getSelection().extend(frame.document.body, 0);
else
frame.getSelection().collapseToEnd();
} else if (frame.document.body.createTextRange) {
var range = frame.document.body.createTextRange();
range.moveEnd('character', frame.document.body.innerHTML.length);
range.collapse(false);
range.select();
}
} else {
frame.document.body.blur();
frame.document.body.focus();
}
}
Updated setEditFocus() (Not really necessary now, but since you already have it):
function setEditFocus()
{
focusEditableFrame($(editorFrame));
}

You know how I solved this one? In resetContent(), replace '' with ' ':
if (myIFrame) myIFrame.contentWindow.document.body.innerHTML=' ';
If it works, good. Don't ask why though, it might be one of those Webkit glitches with Range object, file a bug if you will.

Just quickly, can you try adding semicolons to the end of the lines inside your send() function? And see if that works.
function send() {
resetContent();
setEditFocus();
}

Related

JavaScript, Print Screen and copy and paste

I got some code from the internet, below, and used it in a mock exam application I am doing. This is suppose to prevent people from Printing Screen, copying or cutting from the exam page. The code works perfectly well in Internet Explorer but does not work in the other browsers. I need help to make the code below work in the other browsers to avoid cheating at the site during mock exam. Below is the code:
<script type="text/javascript">
function AccessClipboardData() {
try {
window.clipboardData.setData('text', "No print data");
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.description + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
setInterval("AccessClipboardData()", 300);
document.onkeydown = function (ev) {
var a;
ev = window.event;
if (typeof ev == "undefined") {
alert("PLEASE DON'T USE KEYBORD");
}
a = ev.keyCode;
alert("PLEASE DON'T USE KEYBORD");
return false;
}
document.onkeyup = function (ev) {
var charCode;
if (typeof ev == "undefined") {
ev = window.event;
alert("PLEASE DON'T USE KEYBORD");
} else {
alert("PLEASE DON'T USE KEYBORD");
}
return false;
}
Please know that it is entirely impossible to prevent users from copying or screencapping your site from javascript, seeing how they could simply disable js or your function in particular as has been mentioned in the comments already.
If you simply want to discourage people as much as possible you can still use your code, however window.clipboardData.setData only works in IE so it is not strange you would get an error message in other browsers, for thos you would have to use execCommand to copy a set message to the clipboard at you set interval
documnet.execCommand(delete, false, null)
to delete the current selection and then
documnet.execCommand(copy, false, null)
to copy the currently selected text(which you just made sure was nothing)
(for more info on execCommand https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand)
this should work in Firefox, Safari and Chrome, I know of no way to do this in Opera, as neither command will work in that browser
Note however that this will keep overwritting your clipboard as long as the site is open in the browser, so even if someone tried to copy something else entirely they would be unable.
I would like to point out that I provide this function only to show you what the problem with your code, as you will never be able to do what you want to completely without getting people to install third party rights management software on their computer.
I find the following code at Stackoverflow here, by iDhavalVaja and it worked fine.
<script type="text/javascript">
$(function () {
$(this).bind("contextmenu", function (e) {
e.preventDefault();
});
});
</script>
<script type="text/JavaScript">
function killCopy(e) { return false }
function reEnable() { return true }
document.onselectstart = new Function("return false");
if (window.sidebar) {
document.onmousedown = killCopy;
document.onclick = reEnable;
}
</script>
If you just want to get this working in other browsers, maybe use jQuery (something like this):
$(document).keydown(function (e) {
alert("PLEASE DON'T USE KEYBORD");
});

Javascript to detect if user changes tab

I am writing a webpage for online quiz. The basic requirement I have is that it must fire an event(stopping the quiz) if the user changes tabs or opens a news window even without minimizing their browser, i.e if the person is attempting to see the answer from some other window/tab. How can I do that?
Note : Try to avoid including a bleeding edge HTML5 feature in your answer because I want the feature to be supported by all major browsers currently.
You can determine if a tab or window is active by attaching a blur / focus event listener to window.
in jQuery it would be
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});
quoted from this SO answer: https://stackoverflow.com/a/1760268/680578
In 2022 you can use an event listener with the visibilitychange event:
document.addEventListener("visibilitychange", (event) => {
if (document.visibilityState == "visible") {
console.log("tab is active")
} else {
console.log("tab is inactive")
}
});
If you are targeting browsers that support it, you can use the Page Visibility API available in HTML5. It doesn't directly detect tab changes, per-say, but visibility changes. Which would include (but not limited to) tab changes.
See https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
Best native function hands down, no jQuery.
document.hasFocus
Check the pen, check what happens when you go to the link and back to the codepen tab.
https://codepen.io/damianocel/pen/Yxxzdj
With jQuery:
$(window).on('focus', function () {
});
$(window).on('blur', function () {
});
$().focus & $().blur are deprecated.
window onfocus and onblur work just fine:
window.onfocus = function (ev) {
console.log("gained focus");
};
window.onblur = function (ev) {
console.log("lost focus");
};
Working on a similar project. This worked the best. On the highest level component which wouldn't normally rerender, add:
setInterval( checkFocus, 200 );
function checkFocus(){
if(document.hasFocus()==false){
//Do some checking and raise a red flag if this runs during an exam.
}
}
I needed something like this and it seems this behavior is slightly different on each browser.
if (document.hidden !== undefined) { // Opera 12.10 and Firefox 18 and later support
visibilityChange = "visibilitychange";
} else if (document.mozHidden !== undefined) {
visibilityChange = "mozvisibilitychange";
} else if (document.msHidden !== undefined) {
visibilityChange = "msvisibilitychange";
} else if (document.webkitHidden !== undefined) {
visibilityChange = "webkitvisibilitychange";
} else if (document.oHidden !== undefined) {
visibilityChange = "ovisibilitychange";
}
document.addEventListener(visibilityChange, function(event) {
handleVisibilityChange();
}, false);
I have an example you can check:
https://jsfiddle.net/jenol/4g1k80jq/33/

JS Busy loading indicator ignore middle click

My busy loading indicator basically works by detecting clicks. However, I just noted that when I middle click an item, it opens a link in a new tab and then the loading indicator shows up forever. How can I tell JS to ignore the middle mouse button?
window.onload = setupFunc;
function setupFunc() {
document.getElementsByTagName('body')[0].onclick = clickFunc;
hideBusysign();
Wicket.Ajax.registerPreCallHandler(showBusysign);
Wicket.Ajax.registerPostCallHandler(hideBusysign);
Wicket.Ajax.registerFailureHandler(hideBusysign);
}
function hideBusysign() {
document.getElementById('busy').style.display ='none';
}
function showBusysign() {
document.getElementById('busy').style.display ='inline';
}
function clickFunc(eventData) {
var clickedElement = (window.event) ? event.srcElement : eventData.target;
if (clickedElement.tagName.toUpperCase() == 'BUTTON' || clickedElement.tagName.toUpperCase() == 'A' || clickedElement.parentNode.tagName.toUpperCase() == 'A'
|| (clickedElement.tagName.toUpperCase() == 'INPUT' && (clickedElement.type.toUpperCase() == 'BUTTON' || clickedElement.type.toUpperCase() == 'SUBMIT'))) {
showBusysign();
}
}
You can try to, but it won't work very well with all browsers.
This page describes what browsers support disabling the middle mouse button via JS. Firefox is not one of them...
Another option is to scope the click events to only work on AJAX links/buttons.
For instance (rewriting with jQuery only b/c I'm hopeless without it):
// On load
$(function() {
Wicket.Ajax.registerPreCallHandler(showBusysign);
Wicket.Ajax.registerPostCallHandler(hideBusysign);
Wicket.Ajax.registerFailureHandler(hideBusysign);
});
// Assuming you add an "ajax" class to all appropriate markup (in Wicket)
// .live would be appropriate, too
$('body').delegate('a.ajax, input:button.ajax, input:submit.ajax', 'click', function(){
showBusysign();
});

How to determine which control in window.onbeforeunload in javascript caused the event

I have set up in javascript:
var onBeforeUnloadFired = false;
window.onbeforeunload = function (sender, args)
{
if(window.event){
if(!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
window.event.returnValue = 'You will lose any unsaved changes!'; //IE
}
}
else {
return 'You will lose any unsaved changes!'; //FX
}
windows.setTimeout("ResetOnBeforeUnloadFired()", 1000);
}
function ResetOnBeforeUnloadFired() {
//Need this variable to prevent IE firing twice.
onBeforeUnloadFired = false;
}
I'm trying to achieve an edit screen where the user is warned before navigating away. It works fine except I get the pop up for normal post backs of button clicks. I'm hoping to avoid this so I'm figuring if I could determine which button was pressed it would work.
Does anybody know how to determine which button was pressed in the windows.onbeforeunload?
Alternatively anyone know a better approach to what I'm trying to achieve?
Solved this by putting into an update panel all edit items TextBoxes etc.
Now the windows.onbeforeunload only fires for components external to this.
Another method, if you can't "control" that deep you controls, is to mark somewhat the "good controls", that is the ones which should not trigger the away-navigation logic.
That is easily achievable setting a global javascript variable such as
var isGoodLink=false;
window.onbeforeunload = function (e) {
var message = "Whatever";
e = e || window.event;
if (!isGoodLink) {
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
};
function setGoodLink() {
isGoodLink=true;
}
And add the setGoodLink function on the events you want to keep safe:
<button type="button" onclick="javascript:setGoodLink() ">I am a good button!</button>

Performance issues in javascript onclick handler

I have written a game in java script and while it works, it is slow responding to multiple clicks. Below is a very simplified version of the code that I am using to handle clicks and it is still fails to respond to a second click of 2 if you don't wait long enough. Is this something that I need to just accept or is there a faster way to be ready for the next click?
BTW, I attach this function using AddEvent from the quirksmode recoding contest.
var selected = false;
var z = null;
function handleClicks(evt) {
evt = (evt)?evt:((window.event)?window.event:null);
if (selected) {
z.innerHTML = '<div class="rowbox a">a</div>';
selected = false;
} else {
z.innerHTML = '<div class="rowbox selecteda">a</div>';
selected = true;
}
}
The live code may be seen at http://www.omega-link.com/index.php?content=testgame
You could try to only change the classname instead of removing/adding a div to the DOM (which is what the innerHTML property does).
Something like:
var selected = false;
var z = null;
function handleClicks(evt)
{
var tmp;
if(z == null)
return;
evt = (evt)?evt:((window.event)?window.event:null);
tmp = z.firstChild;
while((tmp != null) && (tmp.tagName != 'DIV'))
tmp = tmp.firstChild;
if(tmp != null)
{
if (selected)
{
tmp.className = "rowbox a";
selected = false;
} else
{
tmp.className = "rowbox selecteda";
selected = true;
}
}
}
I think your problem is that the 2nd click is registering as a dblclick event, not as a click event. The change is happening quickly, but the 2nd click is ignored unless you wait. I would suggest changing to either the mousedown or mouseup event.
I believe your problem is the changing of the innerHTML which changes the DOM which is a huge performance problem.
Yeah you may want to compare the performance of innerHTML against document.createElement() or even:
el.style.display = 'block' // turn off display: none.
Profiling your code may be helpful as you A/B various refactorings:
http://www.mozilla.org/performance/jsprofiler.html
http://developer.yahoo.com/yui/profiler/
http://weblogs.asp.net/stevewellens/archive/2009/03/26/ie-8-can-profile-javascript.aspx

Categories

Resources