Get remote url's last modified date with javascript - javascript

I am trying to get the last date that a remote url was updated using javascript. I have currently come up with this:
function getlastmod(url)
{
var ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", url);
ifrm.setAttribute("id", "oIFRAME");
ifrm.style.display = "none";
var spanTag = document.createElement("span");
spanTag.id = "oSpan";
try
{
var oIFrame = document.getElementById("oIFrame");
var oSpan = document.getElementById("oSpan");
oSpan.innerHTML = oIFrame.src + " last modified " +
oIFrame.document.lastModified;
outUpdate=oSpan;
}
catch(E) {setTimeout("getlastmod();",50);}
}
However, this code seems to always change 'outUpdate' to "undefined". The code is supposed to load the url contents into a frame and then use the document.lastModified function to get the last modified date.
Any ideas on how to fix this?
Thanks!
Josh

You are accessing the element oIFRAME & oSpan before adding them to your document, you have to add these 2 lines before the try block:
document.body.appendChild(ifrm);
document.body.appendChild(spanTag);
The id of your iFrame is oIFRAME and not oIFrame, replace this line:
var oIFrame = document.getElementById("oIFrame");
By
var oIFrame = document.getElementById("oIFRAME");
document is not a property of your iFrame object, contentDocument is. Replace this line
oIFrame.document.lastModified;
by
oIFrame.contentDocument.lastModified;

Why is it in try catch statement? Do you expect it to throw any error? Because you basically rely on that. Do you set initial value for outUpdate? Does it ever enters catch statement?
Why do you have to functions here getlastmod() and getLastModified()?
What happens when you set it to:
var outUpdate = "init";
...
...
getlastmod("/");
console.log("outUpdate is: ", outUpdate);

If your not going to display the page you could save yourself some bandwidth by using xhr.
Here's something to get you going...
manifest.json
{
"name": "Get last modified header with XHR.",
"version": "1.0",
"permissions": [
"tabs", "<all_urls>"
],
"browser_action": {
"default_title": "Get last modified header with XHR.",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version" : 2
}
popup.html
<html>
<head>
<script src="popup.js"></script>
</head>
<body style='width : 400px;'>
<div id="message">Getting File.....</div>
</body>
</html>
popup.js
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.w3schools.com/jsref/lastmodified.htm', true);
xhr.onerror = function() {
var message = document.querySelector('#message');
message.innerText = 'Error getting url';
}
xhr.onreadystatechange = function() {
// readystate 2, headers recieved
if (this.readyState == 2){
var message = document.querySelector('#message');
if (this.getResponseHeader("Last-Modified")){
message.innerText = 'Got the headers\n';
message.innerText += 'Last Last-Modified : ' + this.getResponseHeader("Last-Modified");
} else {
message.innerText = 'Got the headers\n';
message.innerText += 'But there was no Last-Modified\n';
// If the file doesnt exist your still going to get headers
message.innerText += 'Or there was an error in getting the file';
}
// Make sure you access the headers before this abort, as they wont be available afterwards
this.abort();
}
}
xhr.send();

Related

Calling script to clear cookies on specific site in chrome extension

I'm trying to create chrome extension which check if site contains specific element, then clear cookies for this site and refresh.
I created sample extension to delete cookies but in background.js using event chrome.browserAction.onClicked.addListener, :
chrome.browserAction.onClicked.addListener(function(tab) {
var url = tab.url;
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var d = matches && matches[1].replace('www.','');
d = '.'+d;
chrome.cookies.getAll({domain: d}, function (cookies) {
for (var i=0; i<cookies.length; i++) {
var url = "http" + (cookies[i].secure ? "s" : "") + "://" + cookies[i].domain + cookies[i].path;
var cname = cookies[i].name;
chrome.cookies.remove({
"url": url,
"name": cname
});
}
chrome.tabs.reload();
});
});
I took this code from one of posts on stackoverflow, and I was trying to transform it for my need.
In my main extension in background.js I have:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.getSelected(null, function(tab){
chrome.tabs.executeScript(null, {file: 'script.js'});
});
});
and then in script.js:
..some code...
var test = document.getElementById('u_0_c');
if (test === null || test.innerText == "") {
/*------------------------------*/
HERE I WANT TO CLEAR COOKIES
/*----------------------------*/
}
..some code...
I can't use there my code to clear cookies because I got errors like:
Cannot read property 'getSelected' of undefined and similiars.
Thanks for every help ;)

Why doesn't this chrome extension work?

I want to collect the url (var name is 'url') of a webpage into a variable in a chrome extension, together with several user inputs in text inputs, and to send it to a remote php script for processing into an sql database. I am using AJAX to make the connection to the remote server. The popup.html contains a simple form for UI, and the popup.js collects the variables and makes the AJAX connection. If I use url = document.location.href I get the url of the popup.html, not the page url I want to process. I tried using chrome.tabs.query() to get the lastFocusedWindow url - the script is below. Nothing happens! It looks as though it should be straightforward to get lastFocusedWindow url, but it causes the script to fail. The manifest.json sets 'tabs', https://ajax.googleapis.com/, and the remote server ip (presently within the LAN) in permissions. The popup.html has UI for description, and some tags. (btw the response also doesn't work, but for the moment I don't mind!)
//declare variables to be used globally
var url;
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
// Change the value of the outputText field THIS PART IS NOT WORKING YET
function setOutput(){
if(httpObject.readyState == 4){
//document.getElementById('outputText').value = httpObject.responseText;
"Bookmark added to db" = httpObject.responseText; // does this work?
}
}
//put URL tab function here
chrome.tabs.query(
{"active": true, "lastFocusedWindow": true},
function (tabs)
{
var url = tabs[0].url; //may need to put 'var' in front of 'url'
}
);
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
//get url? THIS IS OUTSTANDING - url defined from chrome.tabs.query?
description = document.getElementById('description').value;
tag1 = document.getElementById('tag1').value;
tag2 = document.getElementById('tag2').value;
tag3 = document.getElementById('tag3').value;
tag4 = document.getElementById('tag4').value;
httpObject.open("GET", "http://192.168.1.90/working/ajax.php?url="+url+"&description="+description+"&tag1="+tag1+"&tag2="+tag2+"&tag3="+tag3+"&tag4="+tag4, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput(); //THIS PART IS NOT WORKING
finalString = httpObject.responseText; //NOT WORKING
return finalString; //not working
} //close if
} //close doWork function
var httpObject = null;
var url = null;
var description = null;
var tag1 = null;
var tag2 = null;
var tag3 = null;
var tag4 = null;
// listens for button click on popup.html
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', doWork);
});
Having no responses I first used a bookmarklet instead. The bookmarklet passes the url and title to a php script, which enters them into a db before redirecting the user back to the page they were on.
javascript:(function(){location.href='http://[ipaddress]/bookmarklet.php?url='+encodeURIComponent(location.href)+'&description='+encodeURIComponent(document.title)})()
Then I found this code which works a treat.
var urlOutput = document.getElementById('bookmarkUrl');
var titleOutput = document.getElementById('bookmarkTitle');
if(chrome) {
chrome.tabs.query(
{active: true, currentWindow: true},
(arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }
);
} else {
browser.tabs.query({active: true, currentWindow: true})
.then(logCurrentTabData)
}
const logCurrentTabData = (tabs) => {
currentTab = tabs[0];
urlOutput.value = currentTab.url;
titleOutput.value = currentTab.title;
}

delay in dynamic loading of external Javascript(JSON) file for Phonegap

im trying to load a external js (json) file (PhoneGap app) whose structure is like
var localString ={
"tag1": "Username",
"tag2": "Password",
"submit": "Submit"
}
and using the below code to load it at runtime, the newlocale variable holds the name of the file to be loaded for eg: if locale is english-USA then var resourcePath = en-US.js. The issue is the first time i run this code i get this error "ReferenceError: localstring is not defined" , but it loads the external strings the second time i load it. In between i am calling the external file using "select" tag in html5. Can someone provide some insights on where im going wrong or any pointers to overcome this issue.
var newlocale = window.DeviceCulture.get();
local(newlocale);
function local(lang) {
try {
var resourcePath = lang + '.js';
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = resourcePath;
alert(resourcePath);
document.getElementsByTagName("head")[0].appendChild(scriptEl);
//$('head').append(scriptEl);
//var localString = window.localString;
document.getElementById("07").value = localString['submit'];
} catch (e) {
errorEvent(e);
}
}
Okay I believe the root cause of your problem is that you are appending the tag for the .js file into the head after the page is already loaded. When you first load a page the script tages are downloaded and interpreted in order so b can depend on a. However, the way you are doing it is non-blocking so that the script you load is not fully loaded by the time you get to the next line in your code which tries to access "localString".
To solve this I'd restructure your code somewhat. First forget about making local files JavaScript. Just make them plain text .json files. For example:
{
"tag1": "Username",
"tag2": "Password",
"submit": "Submit"
}
Then I'd load that file using XHR instead of script tag insertion. Something like:
var newlocale = window.DeviceCulture.get();
var localString;
local(newlocale);
function local(lang) {
try {
var resourcePath = lang + '.json';
var request = new XMLHttpRequest();
request.open("GET", resourcePath, true);
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
localString = JSON.parse(request.responseText);
// at this point localString is loaded with the new language
document.getElementById("07").value = localString['submit'];
}
}
}
request.send();
} catch (e) {
errorEvent(e);
}
}
and that should take care of things.

My Firefox extension to inject CSS wont work

I am busy developing a firefox extension. I am using the Add-on Builder
What it will do:
Get an ID from a PHP page (XMLHttpRequest)
Call another function and send that ID with it
That function inserts CSS with a link tag created by javascript
My Problem:
It won't work. If I alert the currenttheme variable, nothing happens. So the XMLHttpRequest doesn't seem to work.
My code:
main.js:
var Widget = require("widget").Widget;
var tabs = require('tabs');
exports.main = function() {
var pageMod = require("page-mod");
var data = require("self").data;
scriptFiles = data.url("s.js");
pageMod.PageMod({
include: "*.facebook.com",
contentScriptWhen: 'ready',
contentScriptFile: scriptFiles
});
s.js
function addCSS(theTheme) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = theTheme+'.css';
(document.head||document.documentElement).appendChild(s);
}
function getData() {
client = new XMLHttpRequest();
try{
client.open('GET','http://localhost:8888/istyla/login/popuplogin/myaccount.php');
} catch (e){
alert( "error while opening " + e.message );
}
client.onreadystatechange = function(){
if (client.readyState ==4){
user_data = client.responseText;
window.user_data = user_data;
var currenttheme = user_data;
window.currenttheme = currenttheme;
addCSS(currenttheme);
}
}
client.send(null);
}
getData();
P.S. The CSS file is in the data folder.
Im very new to this so not sure if I can help. Have you had a look in the error console(ctrl+shift+j) if its complaining about anything? You can console.log() and it will show in here.
Maybe use the Request lib instead of XMLHttpRequest
Here is a snippet from my code:
var Request = require("request").Request;
getUserDetails : function(userID, callback)
{
Request({
url: Proxy.remoteUrl,
content : {command:'getUser',UserID:userID},
onComplete: function(response) {callback(response.json)}
}).get();
}
Content scripts run with the privileges of the page that they are in. So if the page isn't allowed to load http://localhost/, your content script won't be able to do it either. You don't get an immediate error due to CORS but the request will fail nevertheless. What you need to do is to send a message to main.js so that it does the request (extension code is allowed to request any URI) and sends the data back to the content script.
As said, the content script has the same privileged of the web page where is attached, that is meaning you're under the Same Origin Policy.
You can solve the issue as suggested, so sent a message to the add-on code (that is not restricted by the SOP) and post the result back to the content script.
Here an example how the code could be: https://groups.google.com/d/topic/mozilla-labs-jetpack/VwkZxd_mA7c/discussion

document.write in Chrome Extension

I'm new to this so please bear with me. I am trying to write a chrome extension that does the following:
Detect www.website.com/anypage.html. If this website is detected, then do the following.
Don't load the URL.
Instead, write a blank document with a hyperlink to www.website.com/anypage.html?ie=UTF8
The script is set to run at document start (in the manifest).
Here is my code:
Detect URL:
var regExp = /website.com/gi;
var match = 0;
testString = window.location.href.toString();
if(regExp.test(testString) {
match = 1;
Write blank document with link to the URL with the UTF8 encoding tag:
document.write("<a href=" + window.location.href + "?ie=UTF8>Title of Link</a>");
This doesn't work as expected, and just shows a blank page. Anyone have any ideas?
Thanks!
EDIT: Here is the full code:
checklink(); // If there is a match, then checklink will return a 1. If it's already tagged, it will return a 5.
var matchLink = null;
if (checklink() === 1) {
matchLink = window.location.href.toString();
if (checklink() != 1) {
matchLink = null;
function checklink() { //checks to see if the current URL matches website.com
var regExp = /website.com/gi,
testString = window.location.href.toString(),
match = 0,
tagged = 0;
if (regExp.test(testString)) { //if there is a match, returns 1
match = 1;
var regExp2 = /UTF8/gi;
if (regExp2.test(testString)) { //if UTF8 is found, then it returns 5
tagged = 5;
return(match + tagged);
function tagUTF() {
if (matchLink) {
var newLink = matchLink + "?ie=UTF8";
document.write("Link");
if (matchLink) {
tagUTF();
}
The chrome content script has access to the DOM, so you could just replace the contents of the body element of the current page with a new node that has your anchor tag either using dom manipulation methods or innerHTML:
document.body.innerHTML = "<a href=" + window.location.href + "?ie=UTF8>Title of Link</a>";
Please note, this assumes that the JavaScript that is doing the DOM manipulation was properly added for your Chrome extension as a "content script":
http://code.google.com/chrome/extensions/content_scripts.html
EDIT:
Here is the code I used to make it work for me locally:
manifest.json
{
"name": "Test",
"version": "1.0",
"description": "Test",
"permissions": [
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"],
"run_at": "document_end"
}
]
}
content-script.js
document.body.innerHTML = "<a href='test'>test</a>";

Categories

Resources