Chrome extension used to refresh pages - google-chrome

I was trying to develop a Chrome extension that can display me the last 3 news from a soccer news site (obviously the page is not open in any tab), by refreshing every 5 minutes. My ideea was to load the page inside an iframe and, once the page is loaded, access the page DOM and extract only the text nodes with the news. I've tried in many ways using ready and load functions, I tried to follow this solutions here but i always get warnings. My question is: is there a way I can do that without having troubles with cross-domain security? Are there any simple examples i can use?

Here's how you could do it using JQuery (please keep in mind I dont know JQuery, just saw this approach somewhere and thought it might work for you).
I put this in a popup and it worked....
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
function renderNews(newsList){
$('#news').html('');
$(newsList).each(function(i,item){
var link = document.createElement('a');
$(link).attr('href',item.link);
$(link).html(item.description);
$(link).click(function(){
chrome.tabs.create({url:$(this).attr('href')});
});
var linksDate = document.createElement('span');
//$(linksDate).text(item.date);
$(linksDate).text(item.day + '-' + item.month + ' ' + item.hour + ':' + item.minute+' - ');
var listItem = document.createElement('li');
$(listItem).append(linksDate).append(link);
$("#news").append(listItem);
});
}
function getNews() {
$.get("http://www.milannews.it/?action=search&section=32", null, function(data, textStatus)
{
if(data) {
var news=$(data).find(".list").find('li').slice(0,3) ;
$("#status").text('');
var newsList=[];
$(news).each(function(i, item){
var newsItem={};
newsItem.description=$(item).find('a').html();
newsItem.link='http://www.milannews.it/'+$(item).find('a').attr('href');
newsItem.date=$(item).find('span').first().text();
newsItem.day=newsItem.date.split(' ')[0].split('.')[0];
newsItem.month=newsItem.date.split(' ')[0].split('.')[1];
newsItem.hour=newsItem.date.split(' ')[1].split(':')[0];
newsItem.minute=newsItem.date.split(' ')[1].split(':')[1];
newsList[i]=newsItem;
});
renderNews(newsList);
localStorage.setItem('oldNews',JSON.stringify(newsList));
}
});
}
function onPageLoad(){
if (localStorage["oldNews"]!=null) renderNews(JSON.parse(localStorage["oldNews"]));
getNews();
}
</script>
</head>
<body onload="onPageLoad();" style="width: 700px">
<ul id="news"></ul>
<div id="status">Checking for new news...</div>
</body>
</html>
And dont forget to put the urls your getting with the xhr stuff in the permissions part of your manifest....
http://code.google.com/chrome/extensions/xhr.html

Use xhr to load the page and use jQuery or a regex to parse the raw HTML for the data you are looking for.
Keep in mind that the destination site may not want to you access their site in such an automated fashion. Be respectful of their site and resources.

Related

Open the next html file in the directory

I am making a sort of "html app" which involves a very large number of seperate .html files. The 'app' is a sort of 'pro tips' thing, where on every page, is a life tip. I am wondering if there is a code for opening the next html file within the same directory, instead of changing the next tip's in each html file to open it.
Example:
Next Tip
Then in the next tip's html file I would have to put:
Next Tip
And so on:
Next Tip
Sorry if I am not being clear enough.
If you want a client-side only solution this might work for your scenario. Give the a tag an id and add the script part to very page. It will parse your current filename, parses the number from it, adds one and buildsup the next url, replacing that value on your a tag
<html>
<head>
<script src="nav.js"></script>
</head>
<body>
<!-- REMEMBER TO PUT THE ID ON IT -->
<a id="next" href="n.html">next</a>
</body>
</html>
and create a new file called nav.js in your folder and add this code to it:
window.onload = function() {
var a=document.getElementById('next'),
l=document.location.href,
s=Math.max(l.lastIndexOf('\\'),l.lastIndexOf('/')),
d=l.indexOf('.'),
f=l.substring(s+1,l.indexOf('.')),
p=l.substring(0,s+1),
e=l.substring(s+1+f.length, l.length),
n=parseInt(f,10) + 1;
if (a) {
a.href= p + n.toString()+e;
}
};
You could rename all the files into an ordered way, for example tip1.htm, tip2.htm, etc. with Bulk Rename Utility or Ant Renamer if you don't want to get your hands dirty with lots of CMD and PowerShell. After that, add this php code to your main page:
<?php
$file="";
$counter=0;
$arr=array('tip','0','.htm');
function next_file()
{
$counter=$counter+1;
$arr[1]=streval($counter);
include(join("", $arr));
}
?>
Then just call the next_file() function every time the user clicks on the link.
If you have files 1.html, 2.html, etc. this will work.
On your html pages include a blank div (where you want the link to be):
<div id="link"></div>
Include a separate javascript file in the pages:
<script src="app.js"></script>
And then write this in that javascript file:
window.onload = function() {
var maxPages = 3;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
var thenumber = filename.replace(".html", "");
thenumber++;
if (thenumber > maxPages) {
document.getElementById("link").innerHTML = 'Next Tip';
} else {
document.getElementById("link").innerHTML = 'Next Tip';
}
}
Set maxPages so when you get to the end of all the tips, you will go back to the beginning.

getting data from MySQL on jquerymobile only when I refresh the page

ok so I'm trying to load data and move to another page once I'm clicking on a search button in my index.html
this is my search button
<a href="results.html" data-role="button" data-icon="search"
data-iconpos="notext">search</a>
and while it's loading I want the page to run this function and get data
$(function () { $.getJSON("API.php", {
command: "getBusiness",
orig_lat: myPos.lat,
orig_long: myPos.lon,
distance: 0.05 },
function (result) {
$("#locations").html("");
for (var i = 0; i < result.length; i++) {
$("<a href='business.html?ID=" + result[i].id + "&bsnName=" + "'>
<div>" + result[i].bsnName + " " + (parseInt(result[i].distance * 1000))
"</div></a>").appendTo("#locations");}});});
The page is loading without the DB only when I hit refresh it's showing me the result
I'm not sure what's wrong here, should I not use getJSON?? I have seen people talking about .Ajax() is it the same as getJSON() ?
is there a better idea on how to move to another page and simultaneously grab data from DB to the page your going to load on jquerymobile?
I tried to use the same function using onclick it worked when I gave it a div
the rest of the head
<link rel="stylesheet" href="styles/jquery.mobile.structure-1.1.0.min.css" />
<link rel="stylesheet" href="styles/jquery.mobile.theme-1.1.0.min.css" />
<link rel="stylesheet" href="styles/my.css" />
<script src="scripts/jquery-1.7.2.min.js"></script>
<script src="scripts/jquery.mobile-1.1.0.min.js"></script>
<script src="scripts/cordova-1.8.1.js"></script>
<script>
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
var myPos = { lat: 32.0791, lon: 34.8156 };
// Cordova is ready
//
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 10000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
//myPos.lat=position.coords.latitude;
//myPos.lon=position.coords.longitude;
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
Basically when jQuery mobile loads first or index page it load whole head section (Javascript, CSS etc) and body section. but When the user clicks a link in a jQuery Mobile-driven site, the default behavior of the navigation system is to use that link's href to formulate an Ajax request (instead of allowing the browser's default link behavior of requesting that href with full page load).When that Ajax request goes out, the framework will receive its entire text content, but it will only inject the contents of the response's body element.
There can be multiple solutions to this problem e.g.
The simplest approach when building a jQuery Mobile site is to reference the same set of stylesheets and scripts in the head of every page.
Linking without Ajax by using an attribute data-ajax="false" in your link this attribute will load the next page without ajax and animation so both head and body section would load.
If you need to load in specific scripts or styles for a particular page, It is recommended binding logic to the pageInit e.g. "#aboutPage" is id="aboutPage" attribute .
$( document ).delegate("#aboutPage", "pageinit", function() {
//you can place your getJson script here. that will execute when page loads
alert('A page with an ID of "aboutPage" was just created by jQuery Mobile!');
});
So in your case better solution is to bind your ajax call or other particuler script with pageinit event.
You can get help from these pages of jQuery Mobile documentation.
http://jquerymobile.com/demos/1.1.0/docs/pages/page-links.html
http://jquerymobile.com/demos/1.1.0/docs/pages/page-scripting.html

Conflict between jQuery Tools and another jQuery script

I'm using jQuery Tools(specifically, the form validator) and a JQuery Facebook-related script on one page of my website.
Each script requires referencing both an external file in the "head" of my HTML as well as a separate script in the "body" of my HTML.
Here is my code for the scripts in the "body" of my HTML (simplified):
First Script (Facebook script)
`
function init() {
FB.api('/me', function(response) {
$(".s_name").replaceWith('<input type="hidden" name="s_name" id="' + response.name + '" value="' + response.name + '" />');
..do more replaceWith stuff
});
}
//Live update of page as user selects recipient and gift options
$(".jfmfs-friend").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
...do stuff});
`
Second script (jQuery Tools - validator)
`
$("#form").validator({
position: 'top left',
offset: [-5, 0],
message: '<div><em/></div>',
singleError: true
});
`
Everything works correctly until the .click function of the first script is activated. At that point, the validator script stops working. I believe the issue is related to conflicting jQuery $'s, but I'm not sure how to fix it. I've tried using jQuery.noConflict() in various areas, but I haven't been successful and I'm not exactly sure how I should be using it.
Any help would be greatly appreciated!
Try using 'jQuery' in place of all '$' like so:
jQuery(document).ready(function() {}); as against $(document).ready...
I was forced to use the long version during a "conflict" of interest situations.

Using Phonegap, Json and jQuery mobile, how to make a list of titles linking to the individuel articles

I used Json to get data off a site build in Wordpress (using the Json API plugin). I'm using jQuery mobile for the layout of the application in Phonegap. Getting the data to display in Phonegap wasn't the hardest thing to find (code below). But, is it possible to make a list of the titles of different posts and linking them to the specific article and loading the content in a page? In PHP you could just use an argument but is there a way to make something like this work in jQuery mobile?
Here's code I used. Also handy if someones happens to come across this post using google.
<script>
$(document).ready(function(){
var url="http://127.0.0.1:8888/wp/api/get_recent_posts";
$.getJSON(url,function(json){
$.each(json.posts,function(i,post){
$("#content").append(
'<div class="post">'+
'<h1>'+post.title+'</h1>'+
'<p>'+post.content+'</p>'+
'</div>'
);
});
});
});
</script>
EDIT:
I'd like to thank shanabus again for helping me with this. This was the code I got it to work
with:
$(document).ready(function() {
var url="http://127.0.0.1:8888/wpjson/api/get_recent_posts";
var buttonHtmlString = "", pageHtmlString = "";
var jsonResults;
$.getJSON(url,function(data){
jsonResults = data.posts;
displayResults();
});
function displayResults() {
for (i = 0; i < jsonResults.length; i++) {
buttonHtmlString += '' + jsonResults[i].title + '';
pageHtmlString += '<div data-role="page" id="' + $.trim(jsonResults[i].title).toLowerCase().replace(/ /g,'') + '">';
pageHtmlString += '<div data-role="header"><h1>' + jsonResults[i].title + '</h1></div>';
pageHtmlString += '<div data-role="content"><p>' + jsonResults[i].content + '</p></div>';
pageHtmlString += '</div>';
}
$("#buttonGroup").append(buttonHtmlString);
$("#buttonGroup a").button();
$("#buttonGroup").controlgroup();
$("#main").after(pageHtmlString);
}
});
Yes, this is possible. Check out this example: http://jsfiddle.net/shanabus/nuWay/1/
There you will see that we take an object array, cycle through it and append new buttons (and jqm styling). Does this do what you are looking to do?
I would also recommend improving your javascript by removing the $.each and substituting it for the basic for loop:
for(i = 0; i < json.posts.length; i++)
This loop structure is known to perform better. Same with the append method. I've heard time and time again that its more efficient to build up a string variable and append it once rather than call append multiple times.
UPDATE
In response to your comment, I have posted a new solution that simulates loading a Json collection of content objects to dynamically add page elements to your application. It also dynamically generates the buttons to link to them.
This works if you do it in $(document).ready() and probably a few other jQM events, but you may have to check the documentation on that or call one of the refresh content methods to make the pages valid.
http://jsfiddle.net/nuWay/4/
Hope this helps!

Relative URL to a different port number in a hyperlink?

Is there a way without Javascript / server-side scripting to link to a different port number on the same box, if I don't know the hostname?
e.g.:
Look at the other port
(This example does't work as it'll just treat :8080 as a string I want to navigate to)
How about these:
Modify the port number on click:
Look at another port
However, if you hover your mouse over the link, it doesn't show the link with new port number included. It's not until you click on it that it adds the port number. Also, if the user right-clicks on the link and does "Copy Link Location", they get the unmodified URL without the port number. So this isn't ideal.
Here is a method to change the URL just after the page loads, so hovering over the link or doing "Copy Link Location" will get the updated URL with the port number:
<html>
<head>
<script>
function setHref() {
document.getElementById('modify-me').href = window.location.protocol + "//" + window.location.hostname + ":8080/other/";
}
</script>
</head>
<body onload="setHref()">
Look at another port
</body>
</html>
You can do it easily using document.write and the URL will display correctly when you hover over it. You also do not need a unique ID using this method and it works with Chrome, FireFox and IE.
Since we are only referencing variables and not loading any external scripts, using document.write here will not impact the page load performance.
<script language="JavaScript">
document.write('<a href="' + window.location.protocol + '//' + window.location.hostname + ':8080' + window.location.pathname + '" >Link to same page on port 8080:</a> ' );
</script>
It would be nice if this could work, and I don't see why not because : is a reserved character for port separation inside the URI component, so the browser could realistically interpret this as a port relative to this URL, but unfortunately it doesn't and there's no way for it to do that.
You'll therefore need Javascript to do this;
// delegate event for performance, and save attaching a million events to each anchor
document.addEventListener('click', function(event) {
var target = event.target;
if (target.tagName.toLowerCase() == 'a')
{
var port = target.getAttribute('href').match(/^:(\d+)(.*)/);
if (port)
{
target.href = window.location.origin;
target.port = port[1];
}
}
}, false);
Tested in Firefox 4
Fiddle: http://jsfiddle.net/JtF39/79/
Update: Bug fixed for appending port to end of url and also added support for relative and absolute urls to be appended to the end:
Test absolute
Test relative
Modify the port number on mouseover:
Look at another port
This is an improvement of https://stackoverflow.com/a/13522508/1497139 which doesn't have the draw back of not showing the link correctly.
This solution looks cleaner to me
<a href="#"
onclick="window.open(`${window.location.hostname}:8080/someMurghiPlease`)">
Link to some other port on the same host
</a>
Without JavaScript, you'll have to rely on some server side scripting. For example, if you're using ASP, something like ...
Look at the other port
should work. However, the exact format will depend on the technology you are using.
After wrestling with this I found actually that SERVER_NAME is a reserved variable. So, if you are on page (www.example.com:8080) you should be able to drop the 8080 and invoke another port. For instance this modified code just worked for me and moves me from any base port to port 8069 (replace your port as required)
<div>
<a href="http://<?php print
$_SERVER{'SERVER_NAME'}; ?>:8069"><img
src="images/example.png"/>Example Base (http)</a>
</div>
It's better to get the url from the server variables:
// PHP:
<a href="<?=$_SERVER['SERVER_NAME']?>:8080/index.php">
// .net:
<a href='<%=Request.ServerVariables('SERVER_NAME')%>:8080/index.asp'>
No need of complicated javascript : simply insert a script node after your anchor, then get the node in javascript, and modify its href property with the window.location.origin method.
<a id="trans">Look at the other port</a>
<script>
document.getElementById('trans').href='http://'+window.location.origin+':8081';
</script>
The id property must be unique page wide, so you may want to use other method to retrieve node objects.
Tested with apache and Firefox on Linux.
Based on Gary Hole's answer, but changes urls on page load instead of on click.
I wanted to show the url using css:
a:after {
content: attr(href);
}
So I needed the anchor's href to be converted to contain the actual url that would be visited.
function fixPortUrls(){
var nodeArray = document.querySelectorAll('a[href]');
for (var i = 0; i < nodeArray.length; i++) {
var a = nodeArray[i];
// a -> e.g.: Test
var port = a.getAttribute('href').match(/^:(\d+)(.*)/);
//port -> ['8080','/test/blah']
if (port) {
a.href = port[2]; //a -> Test
a.port = port[1]; //a -> Test
}
}
}
Call the above function on page load.
or on one line:
function fixPortUrls(){var na=document.querySelectorAll('a[href]');for(var i=0;i<na.length;i++){var a=na[i];var u=a.getAttribute('href').match(/^:(\d+)(.*)/);u&&a.href=u[2]&&a.port=u[1];}}
(I'm using for instead of forEach so it works in IE7.)
None of the answers I looked at (and I will say, I didn't read them all) adjust the URL such that a middle click or "open in new tab" would function properly -- only a regular click to follow the link. I borrowed from Gary Greene's answer, and instead of adjusting the URL on-the-fly, we can adjust it when the page loads:
...
<script>
function rewriteRelativePortUrls() {
var links = document.getElementsByTagName("a");
for (var i=0,max=links.length; i<max; i++)
{
var port = links[i].getAttribute("href").match(/^:(\d+)(.*)/);
if (port)
{
newURL = window.location.origin + port[0]
links[i].setAttribute("href",newURL)
}
}
}
</script>
<body onload="rewriteRelativePortUrls()">
...
I also needed the same functionality, but I wanted to also do protocol replacement.
My solution will look for data-samehost-port or data-samehost-protocol and regenerate the href attribute on the anchor tag to use the same current hostname with the specified port and/or protocol.
Here is what I'm using:
...
<script type="text/JavaScript">
/**
In http you cannot make a relative link to the same domain but different port.
This script will take urls that look like this:
[given current url: 'http://some-domain.com:3000/a/path/file.html']
1. <a data-samehost-port="8080" href="/some/path">some link</a>
2. <a data-samehost-protocol="https" href="/some/path">some link</a>
3. <a data-samehost-protocol="https" data-samehost-port="8080" href="/some/path">some link</a>
and make them look like this:
1. some link
2. some link
3. some link
**/
document.addEventListener('DOMContentLoaded', function() {
[... new Set([].concat(
Array.from(document.querySelectorAll('[data-samehost-port]')),
Array.from(document.querySelectorAll('[data-samehost-protocol]'))
))]
Array.from(document.querySelectorAll('[data-samehost-port]')).forEach(e=>{
let port = '80'
let path = e.getAttribute('href')
const {hostname,protocol} = document.location
if(e.hasAttribute('data-samehost-protocol')){
protocol = e.getAttribute('data-samehost-protocol')
e.removeAttribute('data-samehost-protocol')
}
if(e.hasAttribute('data-samehost-port')){
port = e.getAttribute('data-samehost-port')
e.removeAttribute('data-samehost-port')
}
if(port==='80') port=''
e.href = `${protocol}//${hostname}${port?`:${port}`:''}${path}`
})
})
</script>
...