Javascript / Blockchain.info Websocket API Address Subscription - javascript

I am new to bitcoin, Blockchain.info API and javascript, however, i am trying to implement a code that tracks Live Payments notification on a particular bitcoin address. The idea here is... after the user scans the QR image <img src="http://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=12fMma2J15qre9bZPsX3AerdgWd9Poe9ee">, and makes payment to the BTC address, 12fMma2J15qre9bZPsX3AerdgWd9Poe9ee, the Div with ID #websocket will instantly display Live (without refreshing the webpage), the amount of Bitcoins Transaferred to the address, thus switching the initial content of the div from monitoring... to the amount transferred Recieved: 0.003 BTC.
I have written a piece of code ... but i'm not sure what i'm missing. Please Help. Thank you.
The code:
<div class="row">
<div class="col-md-4 ">
<img src="http://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=12fMma2J15qre9bZPsX3AerdgWd9Poe9ee">
<div id="websocket">
Monitoring Transactions ...
</div>
<script>
var btcs = new WebSocket("12fMma2J15qre9bZPsX3AerdgWd9Poe9ee");
btcs.onopen = function() {
btcs.send(JSON.stringify({"op":"addr_sub", "addr":"12fMma2J15qre9bZPsX3AerdgWd9Poe9ee"}));
};
btcs.onmessage = function (onmsg) {
var response = JSON.parse(onmsg.data);
var getOutputs = response.x.out;
var countOuts = getOutputs.length;
for (i=0; i < countOuts; i++){
var outAdd = response.x.out[i].addr;
var address = "12fMma2J15qre9bZPsX3AerdgWd9Poe9ee";
if (outAdd == address){
var amount =response.x.out[i].value;
var calAmount = Amount / 100000000;
document.getElementById("websocket").innerHTML = "Recieved" + calAmount + "BTC";
}
}
};
</script>
</div>
<div class="col-md-8">
<!-- more html stuff goes here -->
</div>
</div>

I don't see anywhere in the code a connection being made to blockchain's api, so I'm guessing this
var btcs = new WebSocket("12fMma2J15qre9bZPsX3AerdgWd9Poe9ee");
should use the api's address instead of the target bitcoin wallet address.

Probably you need to put wss://ws.blockchain.info/inv while starting a new socket at the place of address.

<div class="row">
<div class="col-md-4 ">
<img src="http://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=12fMma2J15qre9bZPsX3AerdgWd9Poe9ee">
<div id="websocket">
Monitoring Transactions ...
</div>
<script>
var btcs = new WebSocket("wss://ws.blockchain.info/inv");
btcs.onopen = function() {
btcs.send(JSON.stringify({"op":"addr_sub", "addr":"12fMma2J15qre9bZPsX3AerdgWd9Poe9ee"}));
};
btcs.onmessage = function (onmsg) {
var response = JSON.parse(onmsg.data);
var getOutputs = response.x.out;
var countOuts = getOutputs.length;
for (i=0; i < countOuts; i++){
var outAdd = response.x.out[i].addr;
var address = "12fMma2J15qre9bZPsX3AerdgWd9Poe9ee";
if (outAdd == address){
var amount =response.x.out[i].value;
var calAmount = Amount / 100000000;
document.getElementById("websocket").innerHTML = "Recieved" + calAmount + "BTC";
}
}
};
</script>
</div>
<div class="col-md-8">
<!-- more html stuff goes here -->
</div>
</div>

Related

click event listener method is not working on a specific div

I am trying to add an event listener to my "degree section div" but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the "degree-section" div but to no avail.
Any kind of help is welcome and appreciated
Code:
let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];
//let wind = document.querySelector('.wind');
async function getUrl(city) {
try {
let theUrl = url + city + '&appid=' + apiKey;
let response = await fetch(theUrl, {
mode: 'cors'
})
let data = await response.json();
//Get data from api and change html content based on the recieved data
let temp_data = data.main.temp
temp.textContent = temp_data;
let feels_like_data = data.main.feels_like;
feels_like.textContent = feels_like_data + "K";
let humidity_data = data.main.humidity;
humidity.textContent = humidity_data;
let {
icon
} = data.weather[0];
locationIcon.innerHTML = `<img src="icons/${icon}.png">`;
//change K to C
degree_section.addEventListener('click', () => {
//logging a message just to check if it is working
console.log("c")
})
} catch (err) {
let error = document.createElement('span')
error.className = "error";
error.textContent = "Location does not exist"
let top_center_div = document.querySelector('.top-center')
top_center_div.appendChild(error)
city_name.textContent = "No city found"
}
}
searchbtn.addEventListener('click', (e) => {
let cityName = city.value;
city_name.textContent = cityName
console.log(cityName)
getUrl(cityName)
})
<body>
<div class="loc-container">
<div class="location">
<h1 class="city-name">City</h1>
<div class="weather-icon"><img src="icons/unknown.png" /></div>
</div>
</div>
<div class="weather-info">
<div class="degree-section">
<h2 class="temp">0.0</h2>
<span>K</span>
</div>
<div class="info-section">
<div class="info-flex">
<h3 class="feels-like">0K</h3>
<h4>Feels Like</h4>
</div>
<div class="info-flex">
<h3 class="humidity">0</h3>
<h4>Humidity</h4>
</div>
<div class="info-flex">
<h3 class="wind">0</h3>
<h4>Wind</h4>
</div>
</div>
</div>
<div class="top-center">
<div class="form">
<input type="text" name="city" id="city" required>
<label for="city" class="label-name"><span class="search-name">Search City...</span></label>
</div>
<!-- <i class="fas fa-search search-btn"></i> -->
<i class="material-icons search-btn" style="font-size: 35px;">search</i>
</div>
<script src="weather.js"></script>
</body>
This is what "data" looks like
{"coord":{"lon":72.8479,"lat":19.0144},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],"base":"stations","main":{"temp":303.14,"feels_like":303.45,"temp_min":301.09,"temp_max":303.14,"pressure":1014,"humidity":45},"visibility":2500,"wind":{"speed":3.09,"deg":120},"clouds":{"all":20},"dt":1638773692,"sys":{"type":1,"id":9052,"country":"IN","sunrise":1638754125,"sunset":1638793848},"timezone":19800,"id":1275339,"name":"Mumbai","cod":200}
Thank you in advance!
I believe the problem is with
let degree_section_span = degree_section.getElementsByTagName('span')[0];
since it selects the wrong element. Try changing it to
let degree_section_span = weather_sec.querySelector('.check');
and see if it works. You can also change the variable name to something more appropriate, while you're at it.
EDIT:
I think this is what you're trying to do. For the sake of siplicity , I removed everything not related to temp:
let target = weather_sec.querySelector("div.check"),
temp_data = data.main.temp;
temp.textContent = temp_data;
target.addEventListener('click', () => {
cel = parseInt(temp_data) - 273.15;
temp.textContent = cel.toFixed(2);
temp.nextElementSibling.textContent = "C";
});
So after 48hrs of debugging I finally figured out what is wrong. If you see in my HTML I have a div.top-center at the bottom. And due to some dimension issues in my css file the height of div.top-center spanned the entire page so essentially all of my divs were being wrapped inside div.top-center so even if I assigned a click event to my div.degree-section the target was always div.top-center and that is why the click event was not showing the proper output.

How to work weather without asking location

i have created weather app, which asks location at all reload " allow or block", when i click block, the weather doesnot work after every reload. the problem is that, i want to change code, i want to work weather without asking allow or block, i want to show it immediately, please help me. thanks.
there is my code
const iconElement = document.querySelector(".weather-icon");
const tempElement = document.querySelector(".temperature-value p");
const descElement = document.querySelector(".temperature-description p");
const locationElement = document.querySelector(".location p");
const notificationElement = document.querySelector(".notification");
// App data
const weather = {};
weather.temperature = {
unit : "celsius"
}
// APP CONSTS AND VARS
const KELVIN = 273;
// API KEY
const key = "82005d27a116c2880c8f0fcb866998a0";
// CHECK IF BROWSER SUPPORTS GEOLOCATION
if('geolocation' in navigator){
navigator.geolocation.getCurrentPosition(setPosition, showError);
}else{
notificationElement.style.display = "block";
notificationElement.innerHTML = "<p>Browser doesn't Support Geolocation</p>";
}
// SET USER'S POSITION
function setPosition(position){
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
getWeather(latitude, longitude);
}
// SHOW ERROR WHEN THERE IS AN ISSUE WITH GEOLOCATION SERVICE
function showError(error){
notificationElement.style.display = "block";
notificationElement.innerHTML = `<p> ${error.message} </p>`;
}
// GET WEATHER FROM API PROVIDER
function getWeather(latitude, longitude){
let api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`;
fetch(api)
.then(function(response){
let data = response.json();
return data;
})
.then(function(data){
weather.temperature.value = Math.floor(data.main.temp - KELVIN);
weather.description = data.weather[0].description;
weather.iconId = data.weather[0].icon;
weather.city = data.name;
weather.country = data.sys.country;
})
.then(function(){
displayWeather();
});
}
// DISPLAY WEATHER TO UI
function displayWeather(){
iconElement.innerHTML = `<img src="icons/${weather.iconId}.png"/>`;
tempElement.innerHTML = `${weather.temperature.value}°<span>C</span>`;
descElement.innerHTML = weather.description;
locationElement.innerHTML = `${weather.city}, ${weather.country}`;
}
// C to F conversion
function celsiusToFahrenheit(temperature){
return (temperature * 9/5) + 32;
}
// WHEN THE USER CLICKS ON THE TEMPERATURE ELEMENET
tempElement.addEventListener("click", function(){
if(weather.temperature.value === undefined) return;
if(weather.temperature.unit == "celsius"){
let fahrenheit = celsiusToFahrenheit(weather.temperature.value);
fahrenheit = Math.floor(fahrenheit);
tempElement.innerHTML = `${fahrenheit}°<span>F</span>`;
weather.temperature.unit = "fahrenheit";
}else{
tempElement.innerHTML = `${weather.temperature.value}°<span>C</span>`;
weather.temperature.unit = "celsius"
}
});
html
<div class="container">
<div class="app-title">
<p>Weather</p>
</div>
<div class="notification"> </div>
<div class="weather-container">
<div class="weather-icon">
<img src="icons/unknown.png" alt="">
</div>
<div class="temperature-value">
<p>- °<span>C</span></p>
</div>
<div class="temperature-description">
<p> - </p>
</div>
<div class="location">
<p>-</p>
</div>
</div>
</div>
Due to security reasons there is no way around the browser asking the user if he wants to disclose his location if you try doing it with javascript.
You might however want to look into geolocation via IP, which is not as exact (and if the user uses a VPN doesnt work at all), but maybe a way to go for you.
This should you get you started: https://whatismyipaddress.com/geolocation
You can also make a get request to http://ip-api.com/json and use the data from it.

Javascript (firebase): how can the firebase database key of a clicked item be obtained?

I have a firebase database structure like this
and I have a loop function
var jobTitle = document.getElementById('jobTitle');
var jobDescription= document.getElementById('jobDescription');
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var ref = database.ref('/Jobs/');
ref.on('value', gotData, errData);
}
})
var jobSnap = {};
function gotData(data) {
var date = Today;
var jobs = data.val();
var keys = Object.keys(jobs);
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
for (var i = 0; i<keys.length; i++) {
var k = keys[i];
var newCard = `
<li class="pos-card" id="pos_1">
<div class="content">
<div class="title new">`+jobs[k].JobTitle+`</div>
<div class="dept">Customer Service</div>
<div class="date">date</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>`+jobs[k].JobSummary+`</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
This is the function that submits the application to the DB under the respective job id.
function newApplication() {
var database = firebase.database();
var applicant_Name = document.getElementById('name').value;
var applicant_Number = document.getElementById('phone').value;
var applicant_email = document.getElementById('email').value;
var AuthorId = firebase.auth().currentUser.uid;
var cover_letter = document.getElementById('cover_letter').value;
var JobId = jobSnap.key;
var postData = {
ApplicantName: applicant_Name,
ApplicantNumber: applicant_Number,
Applicantemail: applicant_email,
Author: AuthorId,
Cover_letter: cover_letter,
};
var newPostKey = firebase.database().ref().child('Applications').push().key;
var updates = {};
updates['/Applications/' + newPostKey] = postData;
updates[ JobId + '/Applications/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
that retrieves all entries in the database Jobs node and display them like this
When a user clicks the apply button on a job an application fades in; all the code that retrieves the Jobs and application are in the same html file. What I need to do is find a way to capture the firebase job key of the job that was clicked so that i can save the job application under the respective jobs. I have tried many methods but still no luck how can I implement this?
You'll need to keep track of the key of each item in the HTML. A common way to do that is by injecting it into the id attribute in the HTML:
var newCard = `
<li class="pos-card" id="${k}">
Then you can use the id when the user clicks on an element to find the item in the database.
A more idiomatic way to write your code would be:
function gotData(data) {
var date = Today;
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
data.forEach(function(jobSnap) { // loop over all jobs
var key = jobSnap.key;
var job = jobSnap.val();
var newCard = `
<li class="pos-card" id="${key}">
<div class="content">
<div class="title new">${job.JobTitle}</div>
<div class="dept">Customer Service</div>
<div class="date">${date}</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>${job.JobSummary}</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
If the list is dynammic then you can assign it a unique id and add onclick listener
In your JS function,
Function name(value)
{
}

Ionic scroll Performance issue

I am developing application in which I have feeds or some timeline. here is my ng-repeat code:
<div ng-repeat="x in feeds" class="fd-feed-card">
<div class="fd-feed-usr-img">
<img ng-src="{{x.user.media[0].small}}" class="fd-img fd-img-br border-style">
</div>
<div class="ft-16 fd-feed-usr-name">
<span><b>{{x.user.name}}</b></span><span class="ft-12 fd-feed-created-time plx prm">{{x.feed.createdTimeStamp | readableTime}}</span>
</div>
<div ng-style="imgStyle">
<img ng-src="{{x.feed.media[0].medium}}" class="fd-img objectcover image-blur">
</div>
<div ng-if="x.feed.total_comments > 0 || x.feed.total_likes >0">
<p class="mll"><span on-tap="openCommentModal(x.feed._id, $index, x.feed)" class="prm" ng-if="x.feed.total_comments > 0">{{x.feed.total_comments}} Comment</span><span ng-if="x.feed.total_likes>0" on-tap="openUserModal(x.feed._id)">{{x.feed.total_likes}} Likes</span>
</p>
</div>
<div class="fd-feed-distance">
<span class="plx prm ft-16">{{x.distance}} <span class="ft-10">mil</span></span>
</div>
</div>
here every feed contains username, userimage and 400*400px image of feed and distance. after this im using ionic infinite scroll like this:
<ion-infinite-scroll on-infinite="getDashboardFeed()" distance="1%" ng-if="!noMoreFeedContent"></ion-infinite-scroll>
in my javascript code, i am calling API with pagination having 5 feeds at a time. here it is my javascript code:
$scope.getDashboardFeed = function(start) {
var _start = start || false;
var params = {}
params.offset = offset;
params.limit = limit;
Posts.getAllFeeds(params).success(function(res) {
if (_start) {
$scope.feeds = [];
}
if (res.data.length < limit) {
$scope.noMoreFeedContent = true;
} else {
$scope.noMoreFeedContent = false;
}
for (var i = 0; i < res.data.length; i++) {
var markerPos = new google.maps.LatLng(res.data[i].feed.location[0], res.data[i].feed.location[1]);
var currentLatLng = new google.maps.LatLng(res.data[i].location.location[0], res.data[i].location.location[1])
var distance = google.maps.geometry.spherical.computeDistanceBetween(markerPos, currentLatLng) * 0.000621371;
res.data[i].distance = distance.toFixed(2);
for (var j = 0; j < res.data[i].feed.likes.length; j++) {
if (uid == res.data[i].feed.likes[j].user) {
res.data[i].isLiked = true;
break;
} else {
res.data[i].isLiked = false;
}
}
$scope.feeds.push(res.data[i]);
}
offset = offset + limit;
if (_start) {
$scope.$broadcast('scroll.refreshComplete');
} else {
$scope.$broadcast('scroll.infiniteScrollComplete');
}
})
.error(function(err) {
})
};
im also calculating distance of every feed based on current location. and checking if i liked the post or not.
Now the problem is when feed is loaded to 25,30 , the scroll becomes laggy in my android . Im also using native scrolling given in this link ,
i have read also more blogs like this
but i didnt get much help. I have to load 1000s of feeds here where every feed contains 400*400px picture.
i also tried collection-repeat. it didnot work either.
Is there any other approach I can try to fix my scroll perfomance?
Anybody can help me with that?
I had same issue, especially when using images in ng-repeat.
Check out my answer here

Trigger a html button inside a web browser control

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();
}

Categories

Resources