Trigger a html button inside a web browser control - javascript

in my web browser control i am accessing a form:
<form role="form">
<div class="form-group">
<input type="text" class="form-control" id="InputEmail1" placeholder="name...">
</div>
<div class="form-group">
<input type="email" class="form-control" id="InputPassword1" placeholder="email...">
</div>
<div class="form-group">
<textarea class="form-control" rows="8" placeholder="message..."></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
How can i trigger this button automatically from vb.net application? how can i set text to the text area? am accessing the text box as follows:
WebBrowser1.Document.GetElementById("InputEmail1").SetAttribute("value", "Sample")
WebBrowser1.Document.GetElementById("InputPassword1").SetAttribute("value", "Sample")
i cannot access button and text area since it does not have an id or name? is their any possibility to do like this?

Your elements need to have IDs and if you doesn't have access to the html code you can enumerate elements like this but you must know which element is the right one:
foreach (HtmlElement element in WebBrowser1.Document.Forms[0].All)
{
if (element.TagName.ToLower() == "textarea".ToLower())
{
element.InnerText = "text";
}
}
for clicking a button try this:
element.InvokeMember("click");

In a lot of web automation, unless you can get the original devs to add ids, you have to navigate the DOM in order to find what you need.
Here is an example of doing that kind of filtering and web automation
var actionPanel = topPanel.insert_Above(40);
var ie = topPanel.add_IE_with_NavigationBar().silent(true);
var server = "http://127.0.0.1.:8080";
Action<string,string> login =
(username, password) => {
ie.open(server + "/jpetstore/shop/signonForm.do");
ie.field("username",username);
ie.field("password",password);
ie.buttons()[1].click();
};
Action loginPlaceAnOrderAndGoToCheckout =
()=>{
ie.open("http://127.0.0.1:8080/jpetstore");
ie.link("Enter the Store").click();
//login if needed
var signOffLink = ie.links().where((link)=> link.url().contains("signonForm.do")).first();
if(signOffLink.notNull())
{
signOffLink.click();
login("j2ee", "pwd1");
}
ie.links().where((link)=> link.url().contains("FISH"))[0].click();
ie.link("FI-FW-01 ").flash().click();
ie.links().where((link)=> link.url().contains("addItemToCart"))[0].flash().click();
ie.links().where((link)=> link.url().contains("checkout.do"))[0].flash().click();
ie.links().where((link)=> link.url().contains("newOrder.do"))[0].flash().click();
};
Action scrollToTotal =
()=>{
var tdElement = ie.elements().elements("TD").toList().Where((element)=> element.innerHtml().notNull() && element.innerHtml().contains("Total:")).first();
tdElement.scrollIntoView();
tdElement.injectHtml_beforeEnd("<h2><p align=right>Look at the Total value from the table above (it should be 18.50)</p><h2>");
};
Action<string> exploit_Variation_1 =
(payload) => {
loginPlaceAnOrderAndGoToCheckout();
ie.buttons()[1].flash().click();
ie.open(server + "/jpetstore/shop/newOrder.do?_finish=true&" + payload);
scrollToTotal();
};
Action<string> exploit_Variation_1_SetTotalPrice =
(totalPrice) => {
var payload = "&order.totalPrice={0}".format(totalPrice);
exploit_Variation_1(payload);
};
Another option (which I also use quite a lot) is to actually use Javascript to do those actions (which is much easier if jQuery is available (or injected) in the target page).
[Test] public void Issue_681__Navigating_libraries_views_folders__Clicking_the_icon_doesnt_work()
{
var tmWebServices = new TM_WebServices();
Func<string, string> clickOnNodeUsingJQuerySelector =
(jQuerySelector)=>
{
ie.invokeEval("TM.Gui.selectedGuidanceTitle=undefined");
ie.invokeEval("$('#{0}').click()".format(jQuerySelector));
ie.waitForJsVariable("TM.Gui.selectedGuidanceTitle");
return ie.getJsObject<string>("TM.Gui.selectedGuidanceTitle");
};
if (tmProxy.libraries().notEmpty())
{
"Ensuring the the only library that is there is the TM Documentation".info();
foreach(var library in tmProxy.libraries())
if(library.Caption != "TM Documentation")
{
"deleting library: {0}".debug(library.Caption);
tmProxy.library_Delete(library.Caption);
}
}
UserRole.Admin.assert();
tmProxy.library_Install_Lib_Docs();
tmProxy.cache_Reload__Data();
tmProxy.show_ContentToAnonymousUsers(true);
ieTeamMentor.page_Home();
//tmWebServices.script_Me_WaitForClose();;
//ieTeamMentor.script_IE_WaitForComplete();
ie.waitForJsVariable("TM.Gui.selectedGuidanceTitle");
var _jsTree = tmWebServices.JsTreeWithFolders();
var viewNodes = _jsTree.data[0].children; // hard coding to the first library
var view1_Id = viewNodes[0].attr.id;
var view5_Id = viewNodes[4].attr.id;
var click_View_1_Using_A = clickOnNodeUsingJQuerySelector(view1_Id + " a" );
var click_View_5_Using_A = clickOnNodeUsingJQuerySelector(view5_Id + " a" );
var click_View_1_Using_Icon = clickOnNodeUsingJQuerySelector(view1_Id + " ins" );
var click_View_5_Using_Icon = clickOnNodeUsingJQuerySelector(view5_Id + " ins" );
(click_View_1_Using_A != click_View_5_Using_A ).assert_True();
(click_View_5_Using_A == click_View_1_Using_Icon).assert_False(); // (Issue 681) this was true since the view was not updating
(click_View_5_Using_A == click_View_5_Using_Icon).assert_True();
}

Related

How do I auto-fill a form using session storage?

<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40" />
function getBooking() {
if (sessionStorage.fname != undefined) {
document.getElementById("confirm_fname").textContent = sessionStorage.fname;
document.getElementById("confirm_lname").textContent = sessionStorage.lname;
document.getElementById("confirm_email").textContent = sessionStorage.email;
document.getElementById("confirm_phone").textContent = sessionStorage.phone;
document.getElementById("confirm_start").textContent = sessionStorage.start;
document.getElementById("confirm_streetname").textContent = sessionStorage.streetname;
document.getElementById("confirm_suburb").textContent = sessionStorage.suburb;
document.getElementById("confirm_state").textContent = sessionStorage.state;
document.getElementById("confirm_postcode").textContent = sessionStorage.postcode;
document.getElementById("confirm_skill").textContent = sessionStorage.skill;
document.getElementById("confirm_other").textContent = sessionStorage.other;
document.getElementById("confirm_otherbox").textContent = sessionStorage.otherbox;
document.getElementById("a_fname").value = sessionStorage.fname;
document.getElementById("a_lname").value = sessionStorage.lname;
document.getElementById("a_email").value = sessionStorage.email;
document.getElementById("a_phone").value = sessionStorage.phone;
document.getElementById("a_start").value = sessionStorage.start;
document.getElementById("a_streetname").value = sessionStorage.streetname;
document.getElementById("a_suburb").value = sessionStorage.suburb;
document.getElementById("a_state").value = sessionStorage.state;
document.getElementById("a_postcode").value = sessionStorage.postcode;
document.getElementById("a_skill").value = sessionStorage.skill;
document.getElementById("a_other").value = sessionStorage.other;
document.getElementById("a_otherbox").value = sessionStorage.otherbox;
}
}
How can I, using an external JavaScript file, use session storage to auto-fill a form if the user had already filled out the form in the same browser session? I've already got code that stores the values in session storage if the form is validated correctly, so how would I go about doing this?
If more or less information is needed, please let me know.
Note: no jQuery or inline Javascript please.
Both sessionStorage and localStorage have functions called getItem for retrieving data and setItem for storing data.
Along with some other useful functions.
So, for this case, it seems you need:
document.getElementById("a_fname").value = sessionStorage.getItem("fname");
And same goes for all the rest.
Check this out for more information.
You looking for localStorage methods: getItem(key), setItem(key, value). A little late but one thing i noticed. Maybe it's still helpful for your example. if there are so many elements i would do it through a loop. like for example:
<div id="confirm_fname">First Name</div>
<div id="confirm_lname">Last Name</div>
<div id="confirm_email">Email</div>
...
<script>
const keyNames = [
{k1: 'confirm_fname', k2: 'fname'},
{k1: 'confirm_lname', k2: 'lname'},
{k1: 'confirm_email', k2: 'email'}
]
keyNames.map(function (key) {
sessionStorage.setItem(key.k2, Math.random()); // set to localStorage
document.getElementById(key.k1).textContent = sessionStorage.getItem(key.k2); // get from localStorage
})
</script>
It's make the code shorter and you can easily handel the elements.

How to fix Form action with method get

I have a small issues with my code.
Basically, I have a form in my index.html file:
The form from page 1 is the following:
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search"></button>
</form>
For this form, I want to use OpenWeatherMap API in order to get some weather data. My problem is the following:
I want to get what the user inputs in the form, which I think I can get by using, for example:
var searchInput = document.getElementById("searchInput");
In this variable I can store the location.
And this variable, I want to append to the link that does fetch the data from the API, in the javascript code.
When the user inputs, for example: New York, and press Search, the form action should redirect him to page2.html, where there I can show the weather data.
How can I show that weather data in the page2, with the location input from page1? I tried many times but no luck.
Some Javascript code down below:
let units = 'metric';
let searchMethod = 'q';
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
function searchWeather(searchTerm) {
fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`).then(result => {
return result.json();
}).then(result => {
init(result);
})
}
function init(resultFromServer){
let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader');
let temperatureElement = document.getElementById('temperature');
let humidityElement = document.getElementById('humidity');
let windSpeedElement = document.getElementById('windSpeed');
let cityHeader = document.getElementById('cityHeader');
let weatherIcon = document.getElementById('documentIconImg');
weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png';
let resultDescription = resultFromServer.weather[0].description;
weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);
temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '&#176' + " C";
windSpeedElement.innerHTML = 'Winds at ' + Math.floor(resultFromServer.wind.speed) + ' mph';
cityHeader.innerHTML = resultFromServer.name;
humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity + '%';
}
That is some javascript code which should get the weather data.
Then, in page2, I have the following in HTML:
<div id = "weatherContainer">
<div id = "weatherDescription">
<h1 id = "cityHeader"></h1>
<div id= "weatherMain">
<div id = "temperature"></div>
<div id = "weatherDescriptionHeader"></div>
<div><img id = "documentIconImg"></div>
</div>
<hr>
<div id = "windSpeed" class = "bottom-details"></div>
<div id = "humidity" class = "bottom-details">></div>
</div>
</div>
I expected to have the weather data in page2, where the divs are.
Can somebody give me an advice, please?
Thank you!
Since the form in page1 doesn't exist in page 2, remove
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
instead put
ley searchTerm = new URLSearchParams(location.search).get('location');
searchWeather(searchTerm);
Explanation
When the page 1 form is submitted, it will load page2 like
page2.html?location=xxxx
where xxxx is the value of the <input name='location' ...
location.search will be ?location=xxxx
URLSearchParams makes dealing with these (when you have more than one especially) easier than the old method of splitting/decoding/jumping through hoops
We can simply just submit the form and get the current form input from url on page2.html
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search">Search</button>
</form>
And on the load of page2.html (before your ajax call), we can get the 'searchInput' (location) from URL by following:
<script>
let params = (new URL(document.location)).searchParams;
var searchInput= params.get('location');
</script>
Now, we can use 'searchInput' param for your api call and fetch the result.

Storage and show multiple outputs

I have a simple text input where users type anything and after sumbitting text appear on a page and stays there, which I done with localStorage, but after refreshing the page only last typed input is showing, Ill post my code to be more specific:
HTML:
<body>
<input id="NewPostField" type="text" value="">
<button onclick="myFunction()">Post</button>
<div id="Posts"></div>
</body>
JavaScript:
function myFunction() {
var NewPostField =
document.getElementById("NewPostField");
var newPost = document.createElement("p");
localStorage.setItem('text',
NewPostField.value);
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
(function() {
const previousText = localStorage.getItem('text');
if (previousText) {
var NewPostField = document.getElementById("NewPostField");
NewPostField.value = previousText;
myFunction();
}
})();
Any help will be great!
It seems that your code is only storing the last value posted.
To store more than one post, one idea is to stringify an array of values to store in localStorage.
Then, parse that stringified value back into an array as needed.
Here's an example:
function getExistingPosts() {
// fetch existing data from localStorage
var existingPosts = localStorage.getItem('text');
try {
// try to parse it
existingPosts = JSON.parse(existingPosts);
} catch (e) {}
// return parsed data or an empty array
return existingPosts || [];
}
function displayPost(post) {
// display a post
var new_post = document.createElement("p");
new_post.innerHTML = post;
posts.appendChild(new_post);
}
function displayExistingPosts() {
// display all existing posts
var existingPosts = getExistingPosts();
posts.innerHTML = '';
inputPost.value = '';
if (existingPosts.length > 0) {
existingPosts.forEach(function(v) {
displayPost(v);
});
inputPost.value = existingPosts.slice(-1)[0];
}
}
function addPost(post) {
// add a post
var existing = getExistingPosts();
existing.push(post);
localStorage.setItem('text', JSON.stringify(existing));
displayPost(post);
}
function clearPosts() {
// clear all posts
localStorage.removeItem('text');
displayExistingPosts();
}
var posts = document.getElementById("posts");
var inputPost = document.getElementById("input_post");
var btnPost = document.getElementById('btn_post');
var btnClear = document.getElementById('btn_clear');
btnPost.addEventListener('click', function() {
addPost(inputPost.value)
});
btnClear.addEventListener('click', clearPosts);
displayExistingPosts();
<input id="input_post" type="text" value="">
<button type="button" id="btn_post">Post</button>
<button type="button" id="btn_clear">Clear</button>
<div id="posts"></div>
Since localStorage isn't supported in StackSnippets, here's a JSFiddle to help demonstrate.

Parsing JSON from input value in Javascript?

I'm completely new to the subject of JSON and I was wondering how to parse JSON from an input value in my form.
I'm trying to string the inputs into an array like {"task" : "(input) ", "(input) "} {"description" : "(input ", "(input)"}
I tried to follow the same directions as this post: Adding a new array element to a JSON object but they're referring to strings already formulated when I want to be able to parse JSON the same way from an input in my form. I want to be able to save every input and add a new array element the same way.
Bottom code runs smoothly but I'm such a noobie at parsing JSON D: any help is appreciated.
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
myJSON = JSON.stringify(FormData);
localStorage.setItem("formJSON", myJSON);
text = localStorage.getItem("formJSON");
obj = JSON.parse(text);
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(
"Tasks: " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(description);
console.log("Description: " + descriptionArray.join(", "));
};
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit=" return submitForm()">
<label class="required">*Task and Description* </label>
<!first text box>
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!second comment box>
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script type="text/javascript " src="json.js "></script>
</body>
</html>
You should be storing the array of all tasks in localStorage, not just a single task. When the user saves a new task, read the JSON from local storage, parse it, add the new task to the array, and save that.
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
var arrayJSON = localStorage.getItem("formJSON") || "[]";
var taskArray = JSON.parse(arrayJSON);
taskArray.push(FormData);
localStorage.setItem("formJSON", JSON.stringify(taskArray));
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};

Append localstorage data to the body element on All session (Works also with reload)

I have some code from input, and I wanna to save it to some body element.
I can add it to the body, but it disappear when page is reloaded
function store(){
var nameOfbook = document.getElementById("nameOfbook");
var value = localStorage.setItem("nameOfbook", nameOfbook.value);
var storedValueBockName = localStorage.getItem("nameOfbook");
var par = document.createElement('P');
par.innerText = storedValueBockName;
document.body.appendChild(par);
}
<form action="\" class="form-login" method="post" />
<input name="text" type="text" id="nameOfbook" required="" placeholder="Book name" />
<button onclick="store()" type="button">StoreText</button>
</form>
This question is basically asking how to retrieve a stored value from localStorage.
So you're setting the value in localStorage, but when you reload the page, you need to have a script that checks to see if there's a value in localStorage and add that data to your page if it is found there.
I would suggest something like:
<script>
var setText = function(text) {
var par = document.createElement('P');
par.innerText = text;
document.body.appendChild(par);
}
var checkLocalStorage = function() {
var value = localStorage.getItem("nameOfbook")
if (value) {
setText(value)
}
}
checkLocalStorage()
function store(){
var nameOfbook = document.getElementById("nameOfbook");
var value = localStorage.setItem("nameOfbook", nameOfbook.value);
var storedValueBockName = localStorage.getItem("nameOfbook");
setText(storedValueBockName)
}
</script>
So I moved the code that appends the title to the page into its own function so that it can be used by both store() and checkLocalStorage(). checkLocalStorage looks to see if there's a value set for nameOfbook and, if there is, passes that value to setText.
Should do the trick.

Categories

Resources