how to execute javascript in delphi? - javascript

I am coding a small app ,in middle i struck at some point where i have to execute javascript to get my data ?
in my process ,i have to login to some url and then go to some page and have to get data from that . i done all this with indy idhttp ,i got all info except one column which needs javascript to get value ,then i tried using twebbowser to make it work for me ,but how can i use cookies to enabled to webbrowser ?
i navigated browserto('http://mysite.com/login.php user and pass ') ,well its loged in and then i tried to access next link like ('http://mysite.com/link1/example.php')but it directing to login page :(
any help appreciated :)

What is your question now? In the title you ask how to execute JavaScript. Try the following:
uses
MSHTML_TLB, SHDocVw, ShellAPI;
function ExecuteScript(doc: IHTMLDocument2; script: string; language: string): Boolean;
var
win: IHTMLWindow2;
Olelanguage: Olevariant;
begin
if doc <> nil then
begin
try
win := doc.parentWindow;
if win <> nil then
begin
try
Olelanguage := language;
win.ExecScript(script, Olelanguage);
finally
win := nil;
end;
end;
finally
doc := nil;
end;
end;
end;
Sample usage:
IDoc: IHTMLDocument2;
Webbrowser1.Document.QueryInterface(IHTMLDocument2, iDoc);
ExecuteScript(iDoc, 'document.login.submit()', 'JavaScript');
(This, and more, can be found here).
Then in the text you ask how to use cookies (when using TWebBrowser this should happen automatically). When using Indy HTTP, you just have to attach a TIdCookieManager to your TIdHTTPClient instance, thats all (but you probably don't want to use that anyway, due to the script requirement....)

Your best bet would be to automate IE itself. Grab a copy of embeddedwb, drop on a form and navigate to the url which you need to execute something. There is a document property of the component which returns an OLEVariant, use this to execute a DHTML style statement.. something like document.form.submit;.
You can easily hide the window used for automation, one technique I have used is to place it on a new page on a page control, add a second page to display the status, then show the status page and hide the tabs.

Related

How can I execute Javascript methods with AutoHotkey?

I am writing an AutoHotkey script to enter data into an Oracle PeopleSoft application. Rather than trying to locate specific elements on the page, I want to try execute JavaScript commands directly instead.
So instead of using a hardcoded MouseClick, left, 205, 281 to click the "Add New Values" button, I want to directly run submitAction_win0(document.win0,'#ICSwitchMode')
I've tried entering commands directly into the address bar, but this doesn't seem to have any effect.
#k::
jsCommand = javascript:submitAction_win0(document.win0,'#ICSwitchMode');
Send, !d ; places cursor in URL field
Send, %jsCommand%{Enter} ; submit JS command (doesn't work)
Return
According to this AHK thread, it should be possible to accomplish this using a ScriptControl object, but I'm a bit unsure how to use them.
How can I execute JavaScript commands using AutoHotkey?
Per an example I used in a previous question's answer for controlling IE, walking the DOM, etc:
F3::
wb := ComObjCreate("InternetExplorer.Application") ; Create a IE instance
wb.Visible := True
wb.Navigate("http://google.com")
Sleep, 5000
SendInput, This is test.{Enter}
Sleep, 5000
wb.document.getElementById("lst-ib").value := "This is another test."
wb.document.getElementById("_fZl").click()
return

Cucumber+Ruby+Capybara+Selenium: How to make the 'visit' method wait for dynamic content

Here is the issue that has been nagging for weeks and all solutions found online do not seem to work... ie. wait for ajax, etc...
here is versions of gems:
capybara (2.10.1, 2.7.1)
selenium-webdriver (3.0.1, 3.0.0)
rspec (3.5.0)
running ruby 2.2.5
ruby 2.2.5p319 (2016-04-26 revision 54774) [x64-mingw32]
in the env.rb
Capybara.register_driver :selenium do | app |
browser = (ENV['browser'] || 'firefox').to_sym
Capybara::Driver::Selenium.new(app, :browser => browser.to_sym, :resynchronize => true)
Capybara.default_max_wait_time = 5
end
Here is my dynamicpage.feature
Given I visit page X
Then placeholder text appears
And the placeholder text is replaced by the content provided by the json service
and the step.rb
When(/^I visit page X$/) do
visit('mysite.com/productx/')
end
When(/^placeholder text appears$/) do
expect(page).to have_css(".text-replacer-pending")
end
Then(/^the placeholder text is replaced by the content provided by the json service$/) do
expect(page).to have_css(".text-replacer-done")
end
the webpage in question, which I cannot add it here as it is not publicly accessible, contains the following on page load:
1- <span class="text-replacer-pending">Placeholder Text</span>
after a call to an external service (which provides the Json data), the same span class gets refreshed/updated to the following;
2- <span class="text-replacer-done">Correct Data</span>
The problem I have with the "visit" method in capybara + selenium is that as soon as it visits the page, it thinks everything loaded and freezes the browser, and it never lets the service be called to dynamically update the content.
I tried the following solutions but without success:
Capybara.default_max_wait_time = 5
Capybara::Driver::Selenium.new(app, :browser => browser.to_sym, :resynchronize => true)
add sleep 5 after the visit method
wait for ajax solution from several websites, etc...
adding after hooks
etc...
I am at a complete loss why "visit" can't wait or at least provide a simple solution to an issue i am sure is very common.
I am aware of the capybara methods that wait and those that don't wait such as 'visit' but the issue is;
there is no content that goes from hidden to displayed
there is there is no user interaction either, just the content is getting updated.
also unsure if this is a capybara issue or a selenium or both.
Anyhow have insight on any solutions? i am fairly new to ruby and cucumber so specifically what code goes in what file/folder would be much appreciated.
Mel
Restore wait_until method (add it to your spec_helpers.rb)
def wait_until(timeout = DEFAULT_WAIT_TIME)
Timeout.timeout(timeout) do
sleep(0.1) until value = yield
value
end
end
And then:
# time in seconds
wait_until(20) { has_no_css?('.text-replacer-pending') }
expect(page).to have_css(".text-replacer-done")
#maxple and #nattf0dd
Just to close the loop on our issue here...
After looking at this problem from a different angle,
we finally found out Cucumber/Capybara/ is not a problem at all :-)
The issue we are having lies with the browser Firefox driver (SSL related), since we have no issues when running the same test with the Chrome driver.
I do appreciate the replies and suggestions and will keep those in mind for future.
thanks again!

Javascript "value=..." returns blank page

Follow the following steps.
Steps 1:
Go to google.
Open the javascript console.
Enter the command: document.all.q.value = "hello"
As expected the element with a name of "q" (the search field) is set to "hello").
Steps 2:
Go to google.
In the address bar type javascript: document.all.q.value = "hello!"
Press Enter
If your browser is either Internet Explorer, or Google Chrome, the javascript will have replaced the google website with an entirely blank page, with the exception of the word "Hello".
Finally
Now that you've bugged out your browser, go back to Google.com and repeat Steps 1. You should receive an error message "Uncaught ReferenceError: document is not defined (...) VM83:1
Question:
Am I doing something wrong? And is there another method which works, while still using the address bar for JS input?
The purpose of a javascript: scheme URL is to generate a new page using JavaScript. Modifying the existing page with it is something of a hack.
document.all.q.value = "hello!"; evalues as "hello!", so when you visit that URL, a new HTML document consisting solely of the text hello! is generated and loaded in place of the existing page.
To avoid this: Make sure the JS does not return a string. You can do this by using void.
javascript:void(document.all.q.value = "hello!");
When messing around with javascript: in the adressbar some (if not the most) browsers handle it as a new page, so you have to add a window.history.back(); at the end
javascript: document.all.q.value = "hello!"; window.history.back();

What are these Google-calendar events from?

It seems it's fairly common practice to grab the contents of a Google-calendar embed code, and add a stylesheet into it (either manually or through something like a PHP script) and display a custom-styled public calendar.
The odd thing is, I noticed if you click the print button at the top, or the "Google Calendar" in the lower right, it goes to localhost or whatever domain the page is - not the Google calendar.
If you try to trace the "gcal$func$[3]();" onclick through the Chrome devtools, or through Firefox with gcal$func$[3].toSource(); it will not find it or say
"function () {
[native code]
}"
So where is this function coming from, and how can you tweak this to make it open in a new window with the Google url, not the current domain (404)?
According to the Google Calendar embed JS code, the function points to the following code
window.open(Pf(this.c.i.Nb + "/render", "cid", b))
this.c.i.Nb represents the base URL, which is by default the domain where the script runs (in your case that's your domain). However, it's intended to be google.com domain and fortunately, it's very easy to change that. baseURL is one of the parameters in the initialization script (declared in the page you're grabbing) and you just need to configure that to https://www.google.com.
If you use PHP, your code might look like this.
$page = new DOMDocument("1.0", "utf-8");
// grab the Google Calendar code
$page->loadHTMLfile("https://www.google.com/calendar/embed?src=yourcalendar%40gmail.com");
// set up the baseUrl and print the grabbed page
echo str_replace('"baseUrl":"/"', '"baseUrl":"https://www.google.com/"', $page->saveHTML());
Now all the links should work correctly.

javascript and loadUrl error

i know that to run a javascript function in webview we need to load it in loadUrl(). In my program everything works fine javascript gets called when i use it in loadUrl, but instead of running javascript on the same page, loadUrl("javascript:function()") vanishes my previous page and run this javascript "function()" in a totally new blank page..
for eg. i tried to fill a form automatically using command:
view.loadUrl("javascript:document.getElementById('password').value = 'my_passoword'");
what happens is, the page which consists of ID-'password' vanishes and a new blank page generates consisting of 'my_password' only
where is the problem?
Using loadUrl to run javascript loads different page
anonymous self-invoking function works fine.. i.e.
view.loadUrl("javascript:(function(){document.getElementById('password').value = 'sb14november';})()");
and as a loop around i think Bojan Kseneman answer will work too..
thanks to all!! :)
EDIT: This library is only for evaluating JavaScript and it created a new WebView instead of using an existing one :/
You can also try js evaluator library
jsEvaluator.evaluate("put your JavaScript code", new JsCallback() {
#Override
public void onResult(final String result) {
// you get the result here (optional)
}
});

Categories

Resources