Facebook request permissions javascript? - javascript

Trying to do 2 things
request offline and user_events permission
perminant session key
Need a feed from facebook for events and there is no rss for it.
Any help would be greatly appreciated!!!
Currently have the following
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<!--<title>Connect JavaScript - jQuery Login Example</title>-->
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<div>
<button id="login">Login</button>
<button id="logout">Logout</button>
<button id="disconnect">Disconnect</button>
</div>
<div id="fb-root"></div>
<script type="text/javascript">
// initialize the library with the API key
FB.init({ apiKey: 'apikey' });
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function () {
FB.Connect.showPermissionDialog('publish_stream');
});
$('#logout').bind('click', function () {
FB.logout(handleSessionResponse);
});
$('#disconnect').bind('click', function () {
FB.api({ method: 'Auth.revokeAuthorization' }, function (response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api(
{
method: 'fql.query',
//Event pull
query: 'SELECT eid, name, tagline, pic_big, host, description, event_type, event_subtype, start_time, end_time, creator, location, venue FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid =' + FB.getSession().uid + ')'
},
function (response) {
var user = response[0];
$('#user-info').html('eid: ' + user.eid).show('fast');
}
);
}
</script>
</body>
</html>

I don't think this helps with your entire issue, however the login code i've used in the past looks something more like this:
$('#login').bind('click', function () {
FB.init({appId: "<appid goes here>", status: true, cookie: true});
FB.login(function(response) {
if (response.session) {
// user logged in, do whatever here
} else {
// user cancelled login
}
},{perms:"offline_access,user_events"});
return false;
});

Related

Chrome Extension - javascript return results to popup HTML

I am working on a chrome extension and I cannot figure out how to pass the javascript response returned in popup.js back to popup.html (so the user can see the results). I tried adding <div id="tabs"> </div> into popup.html thinking that would dynamically bring back function(tabs) results but it does not, greatly appreciate any insights.
popup.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="myButton.css">
</head>
<body style="background-color:Gray;">
Scan
<script src=popup.js></script>
<div id="tabs"> </div>
</body>
</html>
popup.js
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
var tabURL = tabs[0].url;
var api = "https://api.us-east-2.amazonaws.com..."
console.log(tabURL);
console.log(api)
userdata = {"url":tabURL}
console.log(userdata)
fetch(api, {
method: 'POST',
body: JSON.stringify(userdata),
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
});
You can insert Elements into popup.html with popup.js.
e.g.
function addSpan(response) {
let tabDiv = document.getElementById('tabs');
let newSpan = document.createElement('span');
newSpan.innerText = "Test123".
// newSpan.innerText = response;
tabDiv.append(newSpan);
}

Send Email Directly From JavaScript using EmailJS

Send Email Directly From JavaScript using EmailJS.
Please look the below answer and I'm getting so many comments for malicious attacks.. because this file is loading in browser so malicious user can easily get your key configuration. So, how to avoid it?
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
Hi you can directly send email through using EmailJS without using the server side code. It'll totally client side.
For sending you need to configure below details.
1)First,Go to this site [https://www.emailjs.com/] and create free account.
2)below 'Connect your email service' button click and configure. You'll get 'YOUR_SERVICE_ID'
3)Then 'Create email template' button click and configure. You'll get 'YOUR_TEMPLATE_ID'
4)click on 'Send email from JavaScript' button. You'll get code.
5)You'll get the 'YOUR_USER_ID' in [https://dashboard.emailjs.com/account]
I did all configuration and added code please check. below code.
NOTE : - "Please encrypted or embedded your use_id for malicious attacks."
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("YOUR_USER_ID"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
Using JavaScript can expose your credentials like user id , service id to the public. For this , you can store these keys values in a variable (half value) and then manipulating it in runtime like appending remaining half of the key etc. But its not totally safe.
Code :
<html>
<head>
<title>Contact Us</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
</head>
<body>
<div class="container">
<div class="card col-md-6 offset-md-3" style="margin-top:50px;">
<div class="card-body">
<h2>Contact Us</h2>
<label for="thename">Name</label>
<input type="text" class="form-control" id="thename" placeholder="Enter Name">
<label for="themail">Email:</label>
<input type="email" class="form-control" id="themail" placeholder="Enter Email">
<label for="themsg">Message</label>
<textarea class="form-control" id="themsg" placeholder="Enter Message"></textarea>
<button class="btn btn-danger btn-sm" style="margin-top:10px;" onCLick="sendemail();">Send</button>
</form>
</div>
</div>
</div>
<script>
function sendemail() {
var userid = "YourUserID"
emailjs.init(userid);
var thename = document.getElementById('thename').value;
var themail = document.getElementById('themail').value;
var themsg = document.getElementById('themsg').value;
var validmail = /^w+([.-]?w+)*#w+([.-]?w+)*(.w{2,3})+$/;
if (thename == "") {
alert("Please Enter Name");
}
else if (themail == "" || themail.match(!validmail)) {
alert("Please Enter Valid Email");
}
else if (themsg == "") {
alert("Please Enter Message");
}
else {
var contactdetail = {
from_name: thename,
from_email: themail,
message: themsg
};
emailjs.send('YourServiceID', 'YourTemplateID', contactdetail).then(function (res) {
alert("Email Sent Successfully");
},
reason => {
alert("Error Occur");
})
}
}
</script>
</body>
</html>
Make sure to replace "YourUserID" , "YourServiceID" & "YourTemplateID" with your own ids
Reference : Narendra Dwivedi - Send Email From JavaScript
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("service_ud48moz"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('service_ud48moz', 'template_njhhxon', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>

How to use external object in react?

A third party sent me this script. Basically,
include a script
call the object
onAuthorize will feedback data, then do something with data
Is it a way to integrate it with react? I think I need the data from onAuthorize to update my react state
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>Payment Gateway Test Page</title>
<script src="https://service.com/widget.js">
</script>
<style type="text/css">
iframe{border: 0;height: 50px;}
</style>
</head>
<body>
<div>
* Demo for widget
</div>
<br/>
<script>
// widget
mywidget.Button.render({
Client: {
id: "1234",
name: "testme"
},
payment: function (actions) {
var amountValue = parseFloat(document.getElementById("inp-amount").innerText);
return actions.createQuote(amountValue)
},
onAuthorize: function (data) {
// err
if (data.errorCode) {
this.onError(data);
return;
}
// money we need to pay
var amountValue = parseFloat(document.getElementById("inp-amount").innerText);
// we have such points, converted to money
var pointsDollars = parseFloat(data.pointsBurned * 0.005, 10);
// points to convert
document.getElementById('qp').innerText = data.pointsBurned;
// origPay - new_money = pay_now
document.getElementById('bal').innerText = '$' + (amountValue - pointsDollars);
},
onError: function (data) {
console.log(data);
},
onClicked: function (data) {
// on click
console.log(data);
}
}, "#container"); // container
</script>
<div id="container"></div>
<br/>
<div id="amount">
Checkout: $<span id="inp-amount">1543</span> <br>
Points to redeem: <span id="qp"></span> <br>
<hr>
Balance to pay: <span id="bal"></span> <br>
</div>
</body>
</html>
You could create an event and listen for that event. In onAuthorize you can trigger the event and pass the data.
Add an event in your page (not necessarily in React)
// Create the event
var event = new CustomEvent("authroize-me", { "detail": "some event info" });
React component
constructor() {
super();
this.handleAuthroizeMe = this.handleAuthroizeMe.bind(this);
}
handleAuthroizeMe(data) {
console.log(data);
}
componentDidMount() {
document.addEventListener('authroize-me', this.handleAuthroizeMe);
}
componentWillUnmount() {
document.removeEventListener("authroize-me", this.handleAuthroizeMe);
}
In onAuthorize
onAuthorize: function (data) {
// Dispatch event
document.dispatchEvent(event, data);
}
Another quick and dirty fix.
Expose a function from react component outside the react scope.
window.setAuthorizeState = (data)=> {
this.setState({authorizeState: data});
}
Call setAuthorizeState from onAuthorize
The code can be embedded in a component which renders the container. And in componentDidMount, the script can be placed.
class Widget extends Component {
componentDidMount() {
// script here
}
render() {
return (
<div id="container" />
);
}
}

How to create an array of previously retrieved posts from an AJAX request

Here is the problem I am working on.
Attached is an index.html.
Implement the next and previous buttons to navigate to next/previous posts from the API provider (https://jsonplaceholder.typicode.com).
Create a new tag that displays the current post ID.
Bonus points: Create a new array to store all of the previously retrieved posts, and display them in a list.
The API is from jsonplaceholder.typicode.com, so you don't need to implement that. A jsfiddle would be immensely appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Vue Test</title>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css' />
<div id="app">
<h1>{{ message }}</h1>
<div>
<span>{{post.title}}</span>
</div>
<button v-on:click="previousPost">Previous Post</button> <!-- // new vue directive - v-on:click, also -->
<button v-on:click="nextPost">Next Post</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
***emphasized text***crossorigin="anonymous"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Welcome to Vue!',
post: {},
page: 1
},
mounted: function() {
this.getPost()
},
methods: {
nextPost: function() {
this.page = this.page + 1
this.getPost()
// Implement me
},
previousPost: function() {
// Implement me
this.page = this.page - 1
this.getPost()
},
getPost: function() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/' + this.page,
method: 'GET'
})
.then((data) => {
console.log(data);
this.post = data;
});
}
}
})
</script>
<style>
/* Add any additional styles here */
body {
padding: 20px;
}
div {
margin: 12px 0;
}
</style>
I would also like to know what is meant by the post id over there. I have completed one task which shows the next and previous posts, but the other two tasks I am a little confused.

ASP.Net MVC Scripts not working with controller's default action url. Same is working with controller/action url

When mvc application is queried with controller name alone in the url without specifying action, the page is rendered but ajax/scripts are not working, whereas the same page when queried with action in the url, is working as expected.
Not working url: http://localhost:port/Search --> Page rendering is fine but scripts are not working - Search results are not showing up
Working url: http://localhost:port/Search/Index --> Page and scripts are working as expected - Search results are showing up
C#:
public class SearchController : Controller
{
private readonly List<string> _cars;
public SearchController()
{
_cars = new List<string>{"Corolla","Camry","Civic","Land Rover","Range Rover","Polo"};
}
public ActionResult Index()
{
return View();
}
public async Task<JsonResult> GetMatchingResults(string filter)
{
var results = await Task.Run(() => GetSearchResults(filter));
return new JsonResult() { Data = results,JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
private List<string> GetSearchResults(string filter)
{
var results = _cars.Where(car => car.Contains(filter));
return results.ToList();
}
}
HTML:
<html>
<head>
#using System.Web.Optimization
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/ApplicationScripts/SearchViewJS.js" type="text/javascript"></script>
<title>SearchView</title>
</head>
<body>
<div>
<input class="searchText" type="search" />
</div>
<div>
<input class="searchResults" type="text" />
</div>
</body>
</html>
JS:
$(document).ready(function () {
$(".searchText").on('input', function (event) {
var filter = $(event.currentTarget).val();
search(filter).then(display);
});
function search(filter) {
return $.getJSON('GetMatchingResults/', { 'filter': filter });
}
function display(result) {
$(".searchResults").val(result);
}
})
It is because of the context of
$.getJSON('GetMatchingResults/', { 'filter': filter });
In the first case that will be trying to hit /GetMatchingResults the second tries to hit /search/GetMatchingResults. A fix could be to use
$.getJSON('/search/GetMatchingResults/', { 'filter': filter });
Or even better would be to generate the path from a HTML helper that will route correctly if you update your routing rules. This would look something like
$.getJSON('#Url.Action("GetMatchingResults", "Search")', { 'filter': filter });

Categories

Resources