Execute Ctrl+D on button click - javascript

I am trying to mimic key press events, for instance Ctrl+D on a button click.
It would be great if someone can point me in the right direction on how to achieve the same.

You're not allowed to do that. Imagine all the havoc I could wreak if I could send CTRL-ALT-DEL at will.

The code for triggering a custom event (in this instance, Ctrl+d) is as follows:
var evt = jQuery.Event("keypress");
evt.keyCode = 100; // d
evt.ctrlKey = true;
$(document).trigger(evt);
NB that, as the other answers have said, this will be limited in its impact. You won't be able to affect normal browser functions in this way.

That would be "firing events", though I'm leaving the exercise to you to find the right code.
As the other guy said, you cannot do any kind of thing with it. It is purposefully limited.
However, let's say I have a wysiwyg editor in javascript, which supports receiving ctrl+s and saving, you should be able to fire that yourself and make it save anyway.
At the end, it's a matter of context (focus), and which sometimes fails (again, purposefully).

This will trigger ctrl+d
function btnClick(){
document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd', 'ctrlKey': true}));
}

Related

Insert a text into a textbox and simulate click on the button in Bot Framework's Web Chat

Fiddle here: https://jsfiddle.net/chpaeeL9/1/
Microsoft Bot Framework has a webchat module that allows you to talk to your bot.
When the user clicks the Say Hi button, I want to place some text into the webchat's textbox, and click the Send button inside the webchat using JavaScript.
Sounds like something too easy, but it wasn't. Here's the code that I currently have, and it doesn't work: the click event somehow is not triggered.
$('#sayhibutton').click(function() {
$('.wc-console').addClass('has-text'); // works
$('.wc-shellinput').val("Hi bot!").change(); // works
$('.wc-send').click(); // doesn't work!
$('.wc-send svg').click(); // doesn't work either
});
Update: if that helps, it seems the interface is written using React.
Update: my question is different from my previous question about how to avoid iframes in webchat.
OK, for the lack of a better option my solution was a pretty dirty and ugly one.
Save the code in botchat.js into a file and reference that saved file from the HTML, rather than the CDN version.
Pretty-print the file in Chrome and find the line that says:
e.prototype.sendMessage = function() {
this.props.inputText.trim().length > 0 && this.props.sendMessage(this.props.inputText)
}
Replace the middle line with this:
this.textInput.value.trim().length > 0 && this.props.sendMessage(this.textInput.value)
This basically means to take the message text from this.textInput.value rather than from this.props.inputText, or in other words, take it directly from the textinput's DOM node.
Somehow triggering the change event on a textbox doesn't cause an actual change event on the textbox, which is why we need to do this.
this is an issue with react try this,
var input = document.getElementsByClassName("wc-shellinput")[0];
var lastValue = input.value;
input.value = 'YOUR MESSAGE';
var event = new CustomEvent('input', { bubbles: true });
// hack React15
event.simulated = true;
// hack React16
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
//send the message
$(".wc-send:first").click();
to read more see this post: https://github.com/Microsoft/BotFramework-WebChat/issues/680

Gamepad javascript create event recorder

I'm writing a little javascript game and trying to make it work with a gamepad. The gamepad works (on linux at least). I wrote this code:
var gamePad;
var checkForGamepad;
function startPolling() {
checkForGamepad= setInterval(function () {
gamePad= navigator.webkitGetGamepads && navigator.webkitGetGamepads()[0]
},20)}
function stopPolling(){
clearInterval(checkForGamepad);
checkForGamepad=null;
}
This is for starting to check if there is a gamecontroller connected and I can also stop it (for when I'm in the menu for example). But now I want to write an event recorder. I wrote already one for the keyboard, but that's easy because you have a 'keyup' event. Does anybody have an idea, how to write an event recorder for a gamepad?
My event recorder for my keyboard looks like this:
function gameNavigationKey(evt){
switch (evt.keyCode){
case 32: // spacebar was pressed
//change the gravity
// do some other stuff
break;
.
.
.
}
And in the code when I start my gameloop(), I also call window.addEventListener('keyup',gameNavigationKey,true)
So I want basically the same style for my event recorder with my gamepad.
I know I can read values of keys being pressed on the gamepad using gamePad.buttons[0] returns 0 when not pressed 1 while being pressed. So I think I need to remember the previous state of my key, but still, don't have an idea how to start.
Can somebody please help me creating this event recorder?
Thanks in advance
In the current implementation of the Gamepads with Chrome, at every update you have to call:
navigator.webkitGetGamepads();
It will give you the latest status of the pads. If you want to implement something out of it you will need to compare with the previous status and make your own events.
Firefox doesn't require to call getGamepads at every frame, but updates the object automatically after you implement the events gamepadconnected and gamepaddisconnected.
You can find extra information here:
http://www.html5rocks.com/en/tutorials/doodles/gamepad/
https://developer.mozilla.org/en-US/docs/Web/Guide/API/Gamepad

Web page: detect and block certain keyboard shortcuts

I want to detect and block certain keyboard shortcuts on a web page. For example, say I want to prevent alt+tab for switching apps (just an example, assume any global shortcut).
Here's as far as I can think it out:
attach a keyboard event listener to
document (or window?)
use event.which to check which key
combination was pressed
if it was a blacklisted shortcut,
stop the browser from executing it
But, I don't know how to
A) detect multiple keys (e.g. alt and tab together), or
B) stop them from executing (can I just return false?).
Can anyone tell me how to accomplish the above?
You want to prevent screenshots from being taken? Forget it right now.
No matter what elaborate mechanisms you put into place, they will be trivial to circumvent by un-focusing the browser window (or just the document, e.g. by clicking into the address bar), and pressing the screenshot key then.
There is no chance for you to do this except by installing client software on the computer that controls what the user does, or maybe using some proprietary ActiveX control that makes its contents un-print-screenable. Both approaches are hugely difficult and have tons of downsides.
You cannot block keyboard combinations that belong to the OS. Only keyboard combinations that roam inside the browser and are not OS specific.
If you want to protect your content, don't publish it in public. Or put a decent license on it
// lookup table for keycodes
var key = { s: 83 };
document.onkeydown = function (e) {
// normalize event
e = e || window.event;
// detecting multiple keys, e.g: Ctrl + S
if (e.ctrlKey && !e.altKey && e.keyCode === key.s) {
// prevent default action
if (e.preventDefault) {
e.preventDefault();
}
// IE
e.returnValue = false;
}
};
Detecting Keystrokes Compatibility Table (QuirksMode)

iPhone/iTouch not firing (new Image) request onunload

Hey guys, hope someone can help me out.
I'm making a small application to record clicks, which is going great, until I hit the iPhone/iTouch. I'd like to point out, that I've been testing with an iTouch, and I am just presuming the same thing will happen on a iPhone.
What I have at the moment is something similar to this,
<script>
function save(){
// Capture link, with var mycoords containing string
var a = 'http://mydomain.com/capture.php?co='+mycoords;
var img = new Image(1,1);
// Loads link with params, PHP uses $_GET
img.src = a;
alert('f'); // For testing
}
// alerts 'f', does not send data on device
window.onunload = save;
// alerts 'f', does not send data on device
window.onunload = (function(){
save();
});
// Alerts 'f', does not send data on device
window.addEventListener("unload",save,false);
</script>
This code works on all my desktop browsers, including Safari, but on the iTouch/iPhone, no. If I execute the save() function outside any onunload practice, the data sends just fine. I know the onunload works, due to the alerts. But I am absolutely baffled by image object not working in this instance, yet working everywhere else. I have had a good look about on the net, and have found no solution.
Perhaps someone here can maybe give me a solution or an explanation to why this is happening? I would be very grateful. Thank you for your time.
Basically there is no way to detect onunload reliably, as is answered here: javascript unload event in safari mobile?
If you're trying to track clicks, I would suggest adding a click event handler to the link which would first call your save() function and then it could return true or update the document.location.href to take the user to the final link.

How can I detect changes in location hash?

I am using Ajax and hash for navigation.
Is there a way to check if the window.location.hash changed like this?
http://example.com/blah#123 to http://example.com/blah#456
It works if I check it when the document loads.
But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).
It shows inside the address box, but I can't catch it with JavaScript.
The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.
Update to keep this answer fresh:
If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.
$(window).on('hashchange', function() {
//.. work ..
});
The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.
With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).
In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.
This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.
HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:
Internet Explorer 8
Firefox 3.6
Chrome 5
Safari 5
Opera 10.6
Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
EDIT -
Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/
There are a lot of tricks to deal with History and window.location.hash in IE browsers:
As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.
Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.
However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.
If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)
I know this isn't a real response, but maybe IE-History notes are useful to somebody.
Firefox has had an onhashchange event since 3.6. See window.onhashchange.
I was using this in a react application to make the URL display different parameters depending what view the user was on.
I watched the hash parameter using
window.addEventListener('hashchange', doSomethingWithChangeFunction);
Then
function doSomethingWithChangeFunction () {
let urlParam = window.location.hash; // Get new hash value
// ... Do something with new hash value
};
Worked a treat, works with forward and back browser buttons and also in browser history.
You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.
Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.
The code will look like this:
window.location.watch(
'hash',
function(id,oldVal,newVal){
console.log("the window's hash value has changed from "+oldval+" to "+newVal);
}
);
Then you can test it:
var myHashLink = "home";
window.location = window.location + "#" + myHashLink;
And of course that will trigger your observer function.
Another great implementation is jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.
Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!
var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123
function TrackHash() {
if (document.location != page_url + current_url_w_hash) {
window.location = document.location;
}
return false;
}
var RunTabs = setInterval(TrackHash, 200);
That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.
I've been using path.js for my client side routing. I've found it to be quite succinct and lightweight (it's also been published to NPM too), and makes use of hash based navigation.
path.js NPM
path.js GitHub
SHORT and SIMPLE example
Click on buttons to change hash
window.onhashchange = () => console.log(`Hash changed -> ${window.location.hash}`)
<button onclick="window.location.hash=Math.random()">hash to Math.Random</button>
<button onclick="window.location.hash='ABC'">Hash to ABC</button>
<button onclick="window.location.hash='XYZ'">Hash to XYZ</button>

Categories

Resources