Create url/link that runs specific javascript - javascript

I have a blog set up with homepage that loads the blog entries into the page when the title is clicked (using a javascript function). I would like to be able to send someone a link to a specific entry. In essence is there a way to have a URL that runs enters the the article name into the function. I know this probably doesn't exist so is there a way to achieve this, if not how should I set up my website so that I don't have 50 replications of the 'shell' at each url with the only thing changing is the text inside one element.
Here is a truncated version of the code.
function addArticle (articleName){
var ourRequest = new XMLHttpRequest();
currentArticleId = articleName;
ourRequest.open('GET', 'https://x.neocities.org/' + articleName +'.html');
ourRequest.onload = function(){
var blogPost = ourRequest.responseText;
document.getElementById("on_display").innerHTML = blogPost;
};
ourRequest.send();
}
Note: I have each article stored in its own url which this script grabs.
Thanks for the help!

Related

Share webpages on social media with counter

I'm creating a website that's going to have hundreds of pages. I want each page to be shareable on Facebook and Twitter. I've already created these buttons but I also want to have their respective share counters next to my share buttons. I don't want to use the standard Facebook method they provide because the coding looks bloated.
Right, so after doing some research, I found this example on codepen.
This looks exactly what I want - very simple!
However, I need some clarification and basic help with how this javascript code works:
var permalink = 'http://codepen.io';
var getTwitterCount = function () {
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?
url='+permalink+'&callback=?', function(data){
var twitterShares = data.count;
$('.twitter .share-count').text(twitterShares);
});
};
getTwitterCount();
var getFacebookCount = function () {
$.getJSON('http://graph.facebook.com/?ids='+permalink+'&callback=?',
function(data){
var facebookShares = data[permalink].shares;
$('.facebook .share-count').text(facebookShares);
});
};
getFacebookCount();
This bit of code:
var permalink = 'http://codepen.io';
Does this have to be:
1) the url of the actual page I want shared, eg: http://www.example.com/page-1/
OR
2) Must this be the root of the domain name, eg: http://www.example.com/
?
Or am I missing something else?
If the answer is #1 above, then that means I have to include + edit this line for each page which isn't ideal because I have all my javascript code + plugins in ONE .js file to reduce http requests, so I'd prefer it that I don't have to add this javascript on-page for every page.
It would be the page that you want to share, but you could get around it without using a separate variable for each page by setting it to something like document.location.href for example?

Create a link with POST data from chrome extension

I have created a chrome extension that sends a POST request to some server and gets its response then displays an number badge according to the data.
Now I want to create a link inside the popup.html based on the data used to send the POST request to the server it self so the users can see the data on the website (data source).
This is the code I use in popup.js to send the POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://someserver/path', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
var regex = new RegExp(/ID:\d+/g);
var testregex = regex.test(this.responseText);
if (testregex == true) {
var count = this.responseText.match(/ID:\d+/g).length;
var countext = count.toString();
chrome.browserAction.setBadgeText({text: countext});
} else {
chrome.browserAction.setBadgeText({text: "0"});
}
};
getCurrentTabUrl(function(url) {
var cleanurl = url.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i);
xhr.send('search=' + cleanurl[1] +'&submit=Search');
});
Question is how do I create a link with the same POST data I used before?
Thanks for the help
So, you want to query an external service, then display some information in the popup with a link to more information.
Let's make a scaffold of how you're going to display it. In your popup, include the following:
<div id="data-container">
<div id="data-loading">
<!-- Maybe add an animated spinner here, or something else -->
Loading...
</div>
<div id="data-display">
<!-- Currently empty, will add a link here -->
</div>
</div>
Style this as you wish. Then, from your XHR:
xhr.onload = function () {
/* ... */
// Hide the loading notice
document.getElementById("data-loading").style.display = "none";
// Create the element that will show more details;
// <a href="#"> works okay, but consider making a button
var link = document.createElement("a");
link.href = "#";
link.text = "More details..." // Add data from xhr.responseText?
link.addEventListener("click", clickHandler);
var container = document.getElementById("data-display");
// Make sure the container is empty (in case we're calling this again)
while (container.lastChild) node.removeChild(container.lastChild);
// Append more elements if you want to display some data
container.appendChild(link);
};
Now the interesting part: the clickHandler click handler. To open a new tab from the popup, you should use chrome.tabs.create():
function clickHandler() {
chrome.tabs.create({
url: /* ??? */
});
}
It would be trivial if we wanted to open a normal GET page. To open a POST page, we have to cheat. There are two main possibilities:
Open a javascript: URL that performs a POST. Conceptually easier, but only works for short parameters.
Open a helper page in your extension that will perform POST. This allows you to pass arbitrarily large arguments before the POST happens.
Both are covered in this question: Chrome Extension Development - POST to new tab

DOM contains old element after page update

I'm working on a Chrome Extension (no knowledge required for this question...) and when I visit a page with a certain domain, I have a script that is ran. All is does is grab the attribute value from a <meta> tag in the page:
$('meta[itemprop=contentURL]').attr('content')
This works fine on the first page load. However, located within the page there is also links to related content. If I click one of the related links, the Chrome spinner spins a bit, loads the new content, and updates the URL in the address bar.
However, if I try the above jQuery, I get the old attribute value, not the new one on the new page. Upon using Chrome's Inspect Element, I see that the old attribute value is there, but the new one is there if I use view page source instead.
So it seems that the DOM is old...is there a good way to get an updated DOM? This question goes along with all of the other questions of DOM vs Page Source are different threads that I've looked at but didn't get any answers from.
Is there a good way to get a new DOM with the updated attribute? Thanks.
Edit: Here's what the chrome extension code looks like:
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
// request current page , `cache:false`
$.ajax({url:window.location.href, cache:false})
.done(function(data) {
var content = $(data).filter("meta[itemprop=contentURL]").attr("content");
console.log(content);
});
});
The above code logs undefined. Still looking for a good workaround unless the proposed solution is the best one.
Edit, updated
Try
v2 (javascript)
function done() {
var div = document.createElement("div");
var content = this.responseText;
div.innerHTML = content;
content = div.querySelectorAll("meta[itemprop*=contentURL]")[0].content;
console.log(content);
}
var request = new XMLHttpRequest();
request.onload = done;
request.open("GET", window.location.href + "?=" + (new Date().getTime()), false);
request.send();
v1 (javascript utilizing jquery)
// request current page , `cache:false`
$.ajax({url:window.location.href, cache:false})
.done(function(data) {
var content = $(data).filter("meta[itemprop=contentURL]").attr("content");
console.log(content);
});
See jQuery-ajax-settings at cache

How to use javascript to get information from the content of another page (same domain)?

Let's say I have a web page (/index.html) that contains the following
<li>
<div>item1</div>
details
</li>
and I would like to have some javascript on /index.html to load that
/details/item1.html page and extract some information from that page.
The page /details/item1.html might contain things like
<div id="some_id">
picture
map
</div>
My task is to write a greasemonkey script, so changing anything serverside is not an option.
To summarize, javascript is running on /index.html and I would
like to have the javascript code to add some information on /index.html
extracted from both /index.html and /details/item1.html.
My question is how to fetch information from /details/item1.html.
I currently have written code to extract the link (e.g. /details/item1.html)
and pass this on to a method that should extract the wanted information (at first
just .innerHTML from the some_id div is ok, I can process futher later).
The following is my current attempt, but it does not work. Any suggestions?
function get_information(link)
{
var obj = document.createElement('object');
obj.data = link;
document.getElementsByTagName('body')[0].appendChild(obj)
var some_id = document.getElementById('some_id');
if (! some_id) {
alert("some_id == NULL");
return "";
}
return some_id.innerHTML;
}
First:
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
then
get_information("/details/item1.html", function(text) {
var div = document.createElement("div");
div.innerHTML = text;
// Do something with the div here, like inserting it into the page
});
I have not tested any of this - off the top of my head. YMMV
As only one page exists in the client (browser) at a time and all other (virtual/possible) pages are on the server, how will you get information from another page using JavaScript as you will have to interact with the server at some point to retrieve the second page?
If you can, integrate some AJAX-request to load the second page (and parse it), but if that's not an option, I'd say you'll have to load all pages that you want to extract information from at the same time, hide the bits you don't want to show (in hidden DIVs?) and then get your index (or whoever controls the view) to retrieve the needed information from there ... even though that sounds pretty creepy ;)
You can load the page in a hidden iframe and use normal DOM manipulation to extract the results, or get the text of the page via AJAX, grab the part between <body...>...</body>ยจ and temporarily inject it into a div. (The second might fail for some exotic elements like ins.) I would expect Greasemonkey to have more powerful functions than normal Javascript for stuff like that, though - it might be worth to thumb through the documentation.

Javascript - write links to new tabs

Using Javascript in a firefox extension, I have opened a new tab. I am unaware of how I can write a link to www.google.com and other links (a whole list) in this tab, where the user can click a link and this page will open.
Thank you for your help
so far I had typed in :
var newTabBrowser2 = gBrowser.getBrowserForTab(gBrowser.selectedTab = gBrowser.addTab());
Unfortunately this won't work:
var newTabBrowser2 = gBrowser.getBrowserForTab(gBrowser.selectedTab = gBrowser.addTab());
newdocument=newTabBrowser2.contentDocument.documentElement.textContent;
newdocument.write("google<br>");
newdocument.write("yahoo<br>");
and I've tried this:
var newTabBrowser2 = gBrowser.getBrowserForTab(gBrowser.selectedTab = gBrowser.addTab());
newTabBrowser2.contentDocument.documentElement.innerHTML += "<a
href=\"http://www.google.com\">google";
but that only works when I use the debugger
Any idea why?
Thanks
It's not very clear from your question what you want. Maybe something like:
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write("google<br>");
newdocument.write("yahoo<br>");
newdocument.close();
???
I don't believe you can use textContent to add HTML content to a document - you're possibly better off using the DOM to construct the HTML.
How about something like this (untested):
var newTabBrowser2 = gBrowser.getBrowserForTab(gBrowser.selectedTab = gBrowser.addTab());
newdocument=newTabBrowser2.contentDocument.documentElement;
var link=newdocument.createElement("a");
link.setAttribute("href", "http://www.google.com");
link.textContent="google";
newdocument.appendChild(link);
newdocument.appendChild(newdocument.createElement("br"));
link=newdocument.createElement("a");
link.setAttribute("href", "http://www.yahoo.com");
link.textContent="yahoo";
newdocument.appendChild(link);
newdocument.appendChild(newdocument.createElement("br"));
Alternatively, it may be possible to just write to the innerHtml of the document element.
This looks like the sort of thing you're looking for.
http://mesh.typepad.com/blog/2004/11/creating_a_new_.html
var myUrl = "http://mesh.typepad.com";
var tBrowser = document.getElementById("content");
var tab = tBrowser.addTab(myUrl);
This creates a new tab every time it's run - you can update the url of a pre-existing tab like this:
var uri = "http://mesh.typepad.com";
tBrowser.getBrowserForTab(tab).loadURI(uri);
Finally, you should be able to set the focus to the new tab:
tBrowser.selectedTab = tab;

Categories