How to simulate javascript keypress from Chrome's javascript console (without jQuery)? - javascript-events

I'm trying to use Chrome's developer console to simulate N times (e.g. 10000) javascript's keypress with keycode = 50 (key: "2" in keyboard), not within a single elements, but at page level.
I need to achieve this result without modifying the source code, to test a web application behavior under multiple user interactions.
I found different answers on SO but most of them are based on jQuery.
I tried to use:
var evt = document.createEvent("KeyboardEvent");
>> undefined
evt.initKeyEvent ("keypress", true, true, window,0, 0, 0, 0, 50, 50);
>> undefined is not a function
followed by event dispatch but it doesn't work.
Also I don't know how shall insert a for cycle from Chrome's console.

Related

How to create a KeyEvent for control characters un upercase Ctlr+A and lowercase Ctlr+a

I am developing a custom keyboard using xamarin form and I need to create KeyEvent on my custom renderer for the the Ctrl keys, however I could not find any documentation on how to do it.
I have tried different combination of constructor with the KeyEvent class with no success. For example:
webView.DispatchKeyEvent(new KeyEvent(0, 0, KeyEventActions.Down, KeyEvent.KeyCodeFromString(digit), 0, MetaKeyStates .ShiftLeftOn & MetaKeyStates.CtrlLeftOn));
webView.DispatchKeyEvent(new KeyEvent(0, 0, KeyEventActions.Up, KeyEvent.KeyCodeFromString(digit), 0, MetaKeyStates.ShiftLeftOn & MetaKeyStates.CtrlLeftOn));
I also tried the following for lowercase with no success
webView.DispatchKeyEvent(new KeyEvent(0, 0, KeyEventActions.Down, KeyEvent.KeyCodeFromString(digit), 0, MetaKeyStates.CtrlLeftOn));
webView.DispatchKeyEvent(new KeyEvent(0, 0, KeyEventActions.Up, KeyEvent.KeyCodeFromString(digit), 0, MetaKeyStates.CtrlLeftOn));
This does not provide the control character I am expecting like Ctrl+C or Ctrl+c. I am only getting the event for the actual character like c or C but not the control. I am using this code for a WebView and verifying the the output with JavaScript. The java script reports correctly the character pressed but not the Ctrl, even when checking the ctrlKey property of the javaScript event the flag is set to false.

IUP, menu, webbrowser, tree, tabs

I have such menu situation:
int menu_create(Ihandle *menu)
{
hamburger = IupItem("&Hamburger", "hamburger");
IupSetAttributes(hamburger, "AUTOTOGGLE=YES, RADIO=YES");
char* ce = "Ćev&apčići";
cevapcici = IupItem(utf8_to_cp1250(ce), "cevapcici");
IupSetAttributes(cevapcici, "AUTOTOGGLE=YES, RADIO=YES");
exit = IupItem("Exit\tAlt+F4", "exit");
img4 = IupLoadImage("icons\\delete_16x16.ico");
IupSetAttributeHandle(exit, "TITLEIMAGE", img4);
menu = IupMenu(
IupSubmenu("File",
IupMenu(
hamburger,
cevapcici,
IupSeparator(),
IupItem("Carro&t", "carrot"),
IupSeparator(),
exit,
NULL)),
NULL);
IupSetFunction("exit", (Icallback)mnu_exit);
... etc...
IupSetHandle("menu", menu);
return IUP_DEFAULT;
}
How to get "radio toggle group" functionality with items hamburger and cevapcici so first turns off a second checkmark and opposite. This is my try but it don't work.
2) I try webbrowser example from IUP suite on my windows 7. Problem is that bad black flickering appear's during resize (increase). Also, background of webbrowser flicker black during showing.
I try a same example on Ubuntu and there flickering appear's too but it is not so much visible since background is there white.
Is here any way to get rid of those flickering or if not to get white background of webbrowser window on windows?
3) Since webbrowser is ole object (on windows) is it possible to use say "print preview" or "zoom" function by reference from IUP handle or at any other way like we used to do from MS programming tools?
wbInstance.ExecWB(Exec.OLECMDID_OPTICAL_ZOOM, ExecOpt.OLECMDEXECOPT_DONTPROMPTUSER, 150, DBNull.Value)
4) How can I get key_up event fired from IupTree?
5) Interesting situation with IupTabs:
frame3 = IupHbox(mat, val, NULL);
vboxt1 = IupVbox(frame3, NULL);
vboxt2 = IupVbox(frame3, NULL);
IupSetAttribute(vboxt1, "TABTITLE", "First documents... ");
IupSetAttribute(vboxt2, "TABTITLE", "Second documents... ");
tabs = IupTabs(vboxt1, vboxt2, NULL);
hbox1 = IupHbox(tabs, IupVbox(frame, tree, frame2, NULL), NULL);
dlg = IupDialog(hbox1);
When I set frame3 which should be a same for both tabs my GUI frozes.
However, I have to got same "mat" (IupMatrix) in both tabs because by changing tabs other data load in matrix but similar enough to use same matrix and related functions.
What to do here?
1) The RADIO attribute belongs to the IupMenu, not to the IupItem. This also means that all the IupItems inside that menu will be part of the radio.
A workaround would be to manually unset the other toggle inside the action callback.
2) That flicker is not caused by IUP. Don't know why the native controls are doing it.
3) Yes, but you will have to program that using the OLE API. If you take a look at the IupOleControl and IupWebBrower source code and send me the code to do it, I will be happy to add it to IUP.
4) You don't. Use the K_ANY callbacks.
5) You can not reuse a control in different places in any dialog. So you must have two different frames, with two different matrices. What you can do is to encapsulate your matrix, so the same function will create a matrix with the same attributes and callbacks any time you want one.

Set scrollLeft/scrollTop simultaneously does not work in Safari 6

When setting the scrollTop and scrollLeft parameters in Safari 6 simultaneously, only one of both gets executed, scrolling the page only over one axis. This happens both using native JavaScript, jQuery and the jquery.scrollTo plugin.
Example using jQuery's .animate():
$('body').animate({
'scrollLeft': 100,
'scrollTop': 100
}, {
'duration': 500,
'easing': 'swing'
});
I've set up a demo page here: http://nabble.nl/demo/safari6scrollto/
All examples work fine in all major browsers as expected, in Safari 6 only example no. 4, 6 and 7 work.
Somehow, when loading the demo page in an IFRAME (see bottom of demo page), everything works just fine.
Is this a bug in Safari? If so, how to work around this issue? If not, what is causing it and how can this be resolved?
Other related reports:
https://github.com/flesler/jquery.scrollTo/issues/9
http://forum.jquery.com/topic/scrolltop-scrollleft-not-working-in-safari-6
http://bugs.jquery.com/ticket/12588
I needed to get the jquery.scrollTo plugin working on OSX Mountain Lion, and since I couldn't find the specifics on what is causing this behaviour, I put together a rather ugly workaround. It uses window.scrollTo(x, y) in the step function of jQuery's .animate(), which gives no problems in Safari 6:
var left;
$(window).animate({
'pageXOffset': 100,
'pageYOffset': 100
}, {
duration: 500,
easing: 'swing',
step: function(now, fx) {
if (fx.prop == 'pageXOffset') {
left = now;
} else if (fx.prop == 'pageYOffset') {
window.scrollTo(left, now);
}
}
});
Please note that the step function is called for every animated property, for every element the animation is applied on (in our case just 1: window). Hence the intermediate variable to store the current X position in the animation.
It uses the pageXOffset and pageYOffset properties of the window object, so I don't know how suitable this workaround is for animating the scrollLeft and scrollTop properties of non-window objects.
Anyway, it works for scrolling the entire document, which was all I wanted, and does so very smooth in Safari 6, too!

Extension: How to intercept AJAX responses?

Since extensions can not access unsafeWindow, like Firefox can, to hook into DOM scripts am I looking for other ideas so I come to SO for help!
How about using some code to inject into DOM and sending the intercepted response to a background page, which then does some initial processing before calling a content script for final processing. When done, it answers to the background with a modified response, or the original (it depends), and the background page sends the response back to DOM which handles it to the DOM script response function.
There is just one problem with this, a background page cant communicate with the DOM.
I did a small test with injecting some code, where I output something to the console and an alert. The result wasnt good, as the alert fired but the console was empty - not even an error, which makes me wonder - what console received the output ?
function injectCode(fn){ // Executing an anonymous script
var script = document.createElement('script');
script.type = 'application/javascript';
script.textContent = '(' + fn + ')();';
document.documentElement.appendChild(script); // run the script
document.documentElement.removeChild(script); // clean up
}
var code = function(){
console.log('dom',window);
alert('code injected');
}
injectCode(code);
I also tried addEventListener, with DOMAttrModified DOMSubtreeModified DOMNodeInserted, on DOM elements that change when the DOM ajax response is fully parsed but all failed to fire.
Am I trying to do the impossible, by any means ?
Before continuing, make sure that you know the differences between the script contexts in an extension.
To inject a script from the background page, you have to execute a Content script, which on his turn injects the script as mentioned in your question / here.
Examples (using chrome.tabs.executeScript):
// null = current active tab
// Simple code, background:
chrome.tabs.executeScript(null, {
code: [
'var s = document.createElement("script");',
's.textContent = "console.log(window);";',
'(document.head||document.documentElement).appendChild(s);',
's.parentNode.removeChild(s);'
].join('\n')
});
I can imagine that this method is not doable for a big chuck of code. For a set of pre-defined scripts, you can then use two scripts: the code itself, and a helper script:
// config.js
var fn_code = function() {
console.log(window); ....
};
// helper.js
var s = document.createElement('script');
s.textContent = '(' + fn_code + ')();';
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
// Background:
chrome.tabs.executeScript(null, {file: 'config.js'}, function() {
chrome.tabs.executeScript(null, {file: 'helper.js'});
});
Note: I did not directly link to "config.js", because that complicates the use when using manifest version 2, see "web_accessible_resources".
The previous method only shows how to execute code in one direction (background -> page). If there's a need to activate a background's function from the injected script, you have to define and listen to a custom event handler. See this answer + demo.
Because the code is injected, thus runs in the scope of the page, you have to check the console at the page.
When chrome.tabs.executeScript fails to execute the Content script (eg. because the extension does not have the permission to access a certain page), an error is logged at the console in the background page. This console can be accessed by following these steps.

Unable to remove element loaded by AJAX

I am trying to remove an element on AJAX success which was loaded and attached to the document during a previous AJAX call.
My code looks something like this:
$("#jobs-table-body").on("click", ".one-rc-button", function() {
var ctx = $.parseJSON($(this).siblings(".context").html());
$("#one-rc-candidate-id").val(ctx.candidateId);
$("#one-rc-job-id").val(ctx.jobId);
var loader = $("#wrapper").loader();
$.post($("#one-rc-form").attr("action"), $("#one-rc-form").serialize(), function(result) {
loader.remove();
if(result.success) {
// This works and returns 1
alert($("#candidate-row-" + result.rejectedCandidateId).length);
// This doesn't seem to be doing anything
$("#candidate-row-" + result.rejectedCandidateId).remove();
} else {
//$("#one-jc-messages").html(result.error);
}
});
});
The elements .one-rc-button and #candidate-row-<candidateId> were loaded by a previous AJAX call and they are attached to the document as I can very well see them on my page.
Now, on click of the previously generated .one-rc-button, I trigger a second AJAX call (which works fine) and on result.success, I want to delete the #candidate-row-<candidateId> (which is within the previously generated parent element).
The alert works and returns 1. So I know for sure that the selector is fine and it is matching one unique element.
What I don't understand is why it is unable to remove the element from the page.
Observations
I use Firefox 10.0.2 where this problem is reproducible.
On IE 8, it works (element gets removed)
On debugging the script on Firebug, I can verify that I have got a handle to the right eleemnt.
Try using FireBug to set a breakpoint on that line so you can see exactly what it's getting from that selector. Ideally break up the statement first, like this:
var unwantedDiv = $("#candidate-row-" + result.rejectedCandidateId);
unwantedDiv.remove(); // <-- Set a breakpoint on this line
You can then look at the unwantedDiv variable in the watch pane on the right of the firebug debugger and see what it is, what methods it has/has not got etc. I would assume that you are not getting back exactly what you think you are, possibly because of how you attached the div after the previous AJAX call. More information about JavaScript debugging with FireBug here.
Another option is to turn on strict warnings in the firebug console and see if you get any 'undefined method' errors, which don't stop the show on FireFox, but just bounce you out of that function. Do you get an error in IE?
Solved it by a really ugly workaround. I am still not sure what causes this behaviour.
if(result.success) {
var removeThis = $("#candidate-row-" + result.rejectedCandidateId);
removeThis.remove();
removeThis = $("#candidate-row-" + result.rejectedCandidateId);
if(removeThis.length != 0) {
removeThis.remove();
}
}
Now it works on both Firefox and IE.

Resources