How to retrieve the page title in JavaScript? - javascript

I need a way to retrieve the title of a remote webpage. I found this js on the internet but
someone can tell me what does "$.request("fetch_title", { url: c })" do in this function: ?
function fetch_title() {
var a = $("#url-field"),
b = a.find(".NO_URL"),
a = a.find(".title-status"),
c = $("#url").val();
if (c) {
if (!$('form#newlink textarea[name="title"]').val() || confirm("This will replace your existing title, proceed?"))
a.show().text(reddit.status_msg.loading),
b.hide(),
$.request("fetch_title", { url: c })
} else a.hide(), b.show().text("a url is required")
}

There's no jQuery.request() function in core jQuery, so it's likely implemented by a plug-in. The closest I've found on Google is AmplifyJS, which is described as a "component library for jQuery". However, there's no indication from the documentation that using $ in place of amplify would work.
Taken from the page linked above:
amplify.request is an abstraction layer that can be used for any kind of request for data. amplify.request sets out to separate the data retrieval and caching mechanisms from data requestors.
It seems to be a request for the title of a page based on the specified URL from user input, but the exact specifics of the request would be elsewhere in the code.

To get the title of a page, simply use jquery.get and search for the title in the response like so:
$.get('ajax/test.html', function(data) {
var matches = data.match(/<title>(.*?)<\/title>/);
var title = matches[1];
});
The title will no be in the title variable.

Related

How to add an API Key to a UrlFetchApp in Google Apps Scripts

Solved
Thanks to Dimu Designs for helping out.
The following works.
function myFunction() {
var url = "https://api.fortnitetracker.com/v1/profile/pc/Ninja"; var apiKey = "xxx-xxx-xxx";
var res = UrlFetchApp.fetch(
url,
{
"headers":{
"TRN-Api-Key":apiKey
}
} ); var content = res.getContentText(); Logger.log(res); Logger.log(content);
}
Problem
I'm trying to use Google App Scripts within Google Sheets to call the external Fortnite API to request player data. The bit I'm stuck on how to add an API Key as a header when passing the request.
This is what I've built so far (please no laughing)!...
function myFunction() {
var res =
UrlFetchApp.fetch("https://api.fortnitetracker.com/v1/profile/PC/Ninja?");
var content = res.getContentText(); Logger.log(res);
Logger.log(content);
}
When I try to run this I get back the following error:
Request failed for
https://api.fortnitetracker.com/v1/profile/PC/Ninja? returned code
401. Truncated server response: {"message":"No API key found in request"} (use muteHttpExceptions option to examine full response
I've tried adding my API key in a number of ways based on a number of different posts, but it doesn't work and just confuses me even more (easily done at this point).
Does anyone have any idea how I could go about completing the script to ensure I get information back? :)
---Edit---
First of all, thanks for the help guys, here's where we are at the moment. I've now tried the following:
var url = "https://api.fortnitetracker.com/v1/profile/pc/Ninja"; var apiKey = "xxx-xxxx-xxx";
var response = UrlFetchApp.fetch(
url,
{
"headers":{
"TRN-Api-Key":apiKey
}
} );
Rather than a 401 error, this time a 403 error is being returned.
Note, I've also tried to authenticate the header using "basic" but that doesn't work".
EDIT
I suspect that the API uses a custom header. When you register for an API key you get a string in the following form:
TRN-Api-Key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
I'm guessing here, but the text preceding the colon appears to be a custom header and the string of characters after the colon is the API key.
Without proper documentation this is STILL pretty much a shot in the dark but you can try the following:
var url = "[FORTNITE-API-ENDPOINT]";
var apiKey = "[YOUR-API-KEY]"; // sans header and colon
var response = UrlFetchApp.fetch(
url,
{
"headers":{
"TRN-Api-Key":apiKey
}
}
);
Also, make sure to check out the UrlFetchApp documentation for future reference:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

Issues accessing Facebook profile image

This is the kind of question that I am sure has a simple answer, but I been with this for days now without finding it.
The issue comes when I try to access the picture via the graph API.
According to the graph API the following URL should return a JSON with is_silhouette and url
https://graph.facebook.com/xxx/picture
When I try that in the Graph Explorer it works fine, but when I test the same URL in the browser I get automatically redirected to the URL attribute of the response instead of getting a JSON.
My problem is that I need to access the contents of that JSON to get the URL attribute in order to display the user profile.
My code looks something like this
var fbimage = "https://graph.facebook.com/" + e.uid + "/picture/";
var xhrFbImage = Ti.Network.createHTTPClient({
onload : function() {
jsonData = '';
jsonData = this.responseText;
Ti.API.info("inside FB response...");
Ti.API.info(jsonData);
}
});
xhrFbImage.open("GET", getFbImage);
xhrFbImage.send();
The response is always null
Any tip in the right direction will be really appreciated.
Found the answer.
By adding ?redirect=false I get the actual JSON without the redirect.
So the correct URL to query is
https://graph.facebook.com/xxx/picture?redirect=false
The answer was more visible than I thought. You can refer to it here
https://developers.facebook.com/docs/graph-api/reference/user/picture/

Sending and getting data via $.load jquery

I'm writing a system in HTML5 and Javascript, using a webservice to get data in database.
I have just one page, the index.html, the other pages i load in a <div>
The thing is, i have one page to edit and add new users.
When a load this page for add new user, i do this:
$("#box-content").load("views/motorista_add.html");
But, i want send a parameter or something else, to tell to 'motorista_add.html' load data from webservice to edit an user. I've tried this:
$("#box-content").load("views/motorista_add.html?id=1");
And i try to get using this:
function getUrlVar(key) {
var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null)
r.push(m[1]);
return r;
}
But don't work.
Have i an way to do this without use PHP?
This won't work. Suppose your are loading the motorista_add.html in a page index.html. Then the JS code, the function getUrlVar(), will execute on the page index.html. So document.location that the function will get won't be motorista_add.html but index.html.
So Yes. To do the stuff you are intending, you need server side language, like PHP. Now, on the server side, you get the id parameter via GET variable and use it to build up your motorista_add.php.
You can pass data this way:
$("#box-content").load("views/motorista_add.html", { id : 1 });
Note: The POST method is used if data is provided as an object (like the example above); otherwise, GET is assumed. More info: https://api.jquery.com/load/

how to get facebook page id inside page fan tab using facebook javascript sdk

I'm tring to create a web app that create a fan tabs for facebook pages ...
my problem is ...
I tried this :-
FB.api(
"/{page-id}/feed",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
How to get facebook page id inside page fan tab using facebook javascript sdk ?
this is image describing what I want to do :
http://www.wtttc.com/image.php?id=25
I tried everything but no use :(
thank you
In order to get the page id of fan page, you need to get the signed_request from Facebook.
https://developers.facebook.com/docs/facebook-login/using-login-with-games#checklogin
In fact, this link talk about the cavas page, but it's the same principle for the fan page.
But if you look carefully the way to get this variable, you can find that,
The signed request is sent via an HTTP POST to the URL set as your Canvas URL in the App Dashboard.
Which means, if you want to get a signed request data, you should get it through a HTTP POST.
To get the page id of fan page is not possible just using javascript. Javascript is a client side language, so you can't access the POST data.
What you need to do is just put your javascript code into a .jsp/.php/...or any other server-side language page. Through the server-side language page, you get the signed request and pass it to your javascript code.
Here is an example in JSP:
<%String signedRequest = request.getParameter("signed_request");%><script>window.signedRequest = "<%=signedRequest%>"</script>
And in your javascript, just decode the string you got and it will contain the page id.
var signedRequest = global.signedRequest;
var data1 = signedRequest.split('.')[1];
data1 = JSON.parse(base64decode(data1));
console.log(data1);
Then you can get data like this:
Object {algorithm: "HMAC-SHA256", expires: 1404925200, issued_at: 1404921078, oauth_token: "CAAUT5x1Ujq8BAPzh2ze1b4QTBkcZAtRCW6zA1xJszUasqoEPp…Fy8fAVEZAyhVaxEaq6ZBw6F4bSFI1s8xtXbBLp7oBFL4wZDZD", page: Object…}
algorithm: "HMAC-SHA256"
expires: 1404925200
issued_at: 1404921078
oauth_token: "CAAUT5x1Ujq8BAPzh2ze1b4QTBkcZAtRCW6zA1xJszUasqoEPpFRfM1ln3x9pb7mLBujyug5iHUifSnyxmPHOLe030wI3H5DYXubnxbPhww9aipSnwoEr6lwctuQaGKxYvDBdZCNuFiaYIduORTWirmZC2rKL86Fy8fAVEZAyhVaxEaq6ZBw6F4bSFI1s8xtXbBLp7oBFL4wZDZD"
page: Object
user: Object
user_id: "1519950734891144"
proto: Object
In the page object, you can find page id.
Object {id: "1522695611287219", liked: true, admin: true}
About how to decode the signed request, you can see this link
https://developers.facebook.com/docs/facebook-login/using-login-with-games#checklogin
It's the same way.
Hope this can help you.
You can use fql to get everything you want.
https://developers.facebook.com/docs/reference/fql/
I think this will work for you :
var currentPageID;
var url = window.top.location;
FB.api(
{
method: 'fql.query',
query: "SELECT id FROM object_url WHERE url = '" + url + "'"
},
function(response) {
currentPageID = response[0].id;
}
);
alert(currentPageID);
http://www.wtttc.com/image.php?id=25
window.top.location;
Dose not work inside the facebook page tab ... I traied that before and now ...
Any new Ideas :)
This is a tested solution that uses Facebook Javascript SDK and its undocumented parseSignedRequest method.
Note: you will have to use a bit of server code and this example is for PHP, but it's the easiest I've been able to find out.
Your html page (or whatever you're serving):
<head>
.....
<script type="text/javascript">
// set a variable with the signed_request sent to your app URL by Facebook via POST
var signedRequest = "<?php echo $_REQUEST["signed_request"] ?>";
FB.getLoginStatus(function (response) {
// do not use the response.authResponse.signedRequest but the one above instead
// and let the javascript SDK parse the good signed_request for you
var page = this.parseSignedRequest(signedRequest).page;
// is the current user an admin of this page? true/false
var isAdmin = page.admin;
// do you like this page? true/false
var isLiked = page.liked;
// and here is the Facebook page ID
var pageID = page.id;
if (response.status === 'connected') {
// user is connected
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
}, true);
<script>
Hope this helps. Cheers.
You have to get signed_request POSTed to your app from server side.
https://developers.facebook.com/docs/pages/tabs
Go through the link get some idea about the page tab and page id.

Extracting part of current page's URL in javascript

In ASP.NET MVC 3 site, I open the following uri
http://myserver/incidents/supercompany/register
That page needs to make use of ajax JSON retrieval mechanism with the help of jQuery:
$.getJSON('/Incidents/[[COMPANY NAME GOES HERE]]/SearchPeople/' + request.term, function (data)
I am new to javascript. How can I obtain supercompany part of my current url to build the
/Incidents/supercompany/SearchPeople/ string?
Assuming your URLs follow a logical structure, you can do this
var URLparts = window.location.toString().substr(7).split('/');
And you can now access URLparts[1] to get the company name. Obviously, you need to be able to know that that will ALWAYS be there, but it's a solution if you can guarantee that (eg. with htaccess).

Categories

Resources