EDIT: I have added the response from OMDB
{Response: "False", Error: "Invalid API key!"}
Error: "Invalid API key!"
Response: "False"
I am new to web development and I am trying to build a chrome extension that displays imdb scores on netflix. I am using the OMDB API to do this. At first I got the following error:
"Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ''. This request has been blocked; the content must be served over HTTPS.",
however I just changed the "http" in the url to "https" and it went away. However, now I am getting a 401 error, which I think means my access is being denied.
This is a picture of the full error
Here is the code for the extension
Manifest file:
{
"manifest_version": 2,
"name": "1_ratings_netflix",
"version": "0.1",
"description": "Display imdb ratings on netflix",
"content_scripts": [
{
"matches": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
],
"js": ["content.js"]
}
],
"icons": { "16": "icon16.png", "48":"icon48.png"},
"permissions": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
]
}
Content File:
function fetchMovieNameYear() {
var synopsis = document.querySelectorAll('.jawBone .jawbone-title-link');
if (synopsis === null) {
return;
}
var logoElement = document.querySelectorAll('.jawBone .jawbone-title-link .title');
if (logoElement.length === 0)
return;
logoElement = logoElement[logoElement.length - 1];
var title = logoElement.textContent;
if (title === "")
title = logoElement.querySelector(".logo").getAttribute("alt");
var titleElement = document.querySelectorAll('.jawBone .jawbone-title-link .title .text').textContent;
var yearElement = document.querySelectorAll('.jawBone .jawbone-overview-info .meta .year');
if (yearElement.length === 0)
return;
var year = yearElement[yearElement.length - 1].textContent;
var divId = getDivId(title, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var existingImdbRating = window.sessionStorage.getItem(title + ":" + year);
if ((existingImdbRating !== "undefined") && (existingImdbRating !== null)) {
addIMDBRating(existingImdbRating, title, year);
} else {
makeRequestAndAddRating(title, year)
}
};
function addIMDBRating(imdbMetaData, name, year) {
var divId = getDivId(name, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var synopsises = document.querySelectorAll('.jawBone .synopsis');
if (synopsises.length) {
var synopsis = synopsises[synopsises.length - 1];
var div = document.createElement('div');
var imdbRatingPresent = imdbMetaData && (imdbMetaData !== 'undefined') && (imdbMetaData !== "N/A");
var imdbVoteCount = null;
var imdbRating = null;
var imdbId = null;
if (imdbRatingPresent) {
var imdbMetaDataArr = imdbMetaData.split(":");
imdbRating = imdbMetaDataArr[0];
imdbVoteCount = imdbMetaDataArr[1];
imdbId = imdbMetaDataArr[2];
}
var imdbHtml = 'IMDb rating : ' + (imdbRatingPresent ? imdbRating : "N/A") + (imdbVoteCount ? ", Vote Count : " + imdbVoteCount : "");
if (imdbId !== null) {
imdbHtml = "<a target='_blank' href='https://www.imdb.com/title/" + imdbId + "'>" + imdbHtml + "</a>";
}
div.innerHTML = imdbHtml;
div.className = 'imdbRating';
div.id = divId;
synopsis.parentNode.insertBefore(div, synopsis);
}
}
function getDivId(name, year) {
name = name.replace(/[^a-z0-9\s]/gi, '');
name = name.replace(/ /g, '');
return "aaa" + name + "_" + year;
}
function makeRequestAndAddRating(name, year) {
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + encodeURI(name)
+ "&y=" + year + "tomatoes=true";
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 200) {
var apiResponse = JSON.parse(xhr.responseText);
var imdbRating = apiResponse["imdbRating"];
var imdbVoteCount = apiResponse["imdbVotes"];
var imdbId = apiResponse["imdbID"];
var imdbMetaData = imdbRating + ":" + imdbVoteCount + ":" + imdbId;
window.sessionStorage.setItem(name + ":" + year, imdbMetaData);
window.sessionStorage.setItem("metaScore:" + name + ":" + year, metaScore)
window.sessionStorage.setItem("rotten:" + name + ":" + year, rottenRating);
addIMDBRating(imdbMetaData, name, year);
addRottenRating(rottenRating, name, year);
addMetaScore(metaScore, name, year);
}
};
xhr.send();
}
if (window.sessionStorage !== "undefined") {
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
window.setTimeout(fetchMovieNameYear, 5);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
}
It would be helpful for you to post the request and response for OMDB (you can find them in the "Network" tab in dev tools).
One thing that triggers CORS (cross-origin requests) errors is specifying a content type other than application/x-www-form-urlencoded, multipart/form-data or text/plain. If I recall correctly, the OMDB API will return a JSON response even without specifying the content type of the request, so you should try removing the line:
xhr.setRequestHeader('Content-Type', 'application/json');
More on "Simple Requests" which do not trigger CORS: https://javascript.info/fetch-crossorigin#simple-requests
You also need to get an API key (https://www.omdbapi.com/apikey.aspx) and replace
**{API_KEY}** in your code with the key. You also need to add the t key to your querystring or the title will be appended to your API key.
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + "&t="
+ encodeURI(name) + "&y=" + year + "tomatoes=true";
Related
In Google Apps Script, I'm using some code I adapted from a project I found. It calls an API endpoint and lays out the data in a spreadsheet. I was able to get it to loop through multiple API calls in order to pull data from multiple documents. However, the code breaks if it finds a document with no data. In this case, I want it to just skip that iteration and start again at the next cardIds.forEach iteration.
Here's a link to a sample sheet.
I tried:
if (response == "") {
return;
}
But no dice. Here's the full code (also it's very inefficient. I have params on their twice because I'm not sure how to consolidate them with all the functions inside other functions..)
const DATA_SHEET = "Data";
const USERNAME_CELL = "B1";
const API_TOKEN_CELL = "B2";
const CARD_ID_COL = "Cards!B:B"
const DATA_RANGE = "A4:C"
var getNextPage = function(response) {
var url = response.getAllHeaders().Link;
if (!url) {
return "";
}
return /<([^>]+)/.exec(url)[1];
};
var getIt = function(path, username, apiToken) {
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": {
"Content-Type": "application/json",
"Authorization": "Basic " + Utilities.base64Encode(username + ":" + apiToken),
"x-guru-application": "spreadsheet",
"X-Amzn-Trace-Id": "GApp=spreadsheet"
}
};
var response = UrlFetchApp.fetch(path, params);
var data = JSON.parse(response.getContentText());
// check if there's another page of results.
var nextPage = getNextPage(response);
if (nextPage) {
data.nextPage = nextPage;
};
return data;
};
var getItAll = function(url, username, apiToken, callback) {
var data = [];
while (url) {
var page = getIt(url, username, apiToken);
var startIndex = data.length;
page.forEach(function(a) {
data.push(a);
});
// get the url of the next page of results.
url = page.nextPage;
if (callback) {
// the second parameter is whether we're done or not.
// if there's a url for the next page that means we're not done yet.
callback(data, startIndex, page.length, url ? false : true);
}
}
return data;
};
function eachCard() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(DATA_SHEET);
sheet.getRange(DATA_RANGE).clearContent();
var username = sheet.getRange(USERNAME_CELL).getValue();
var apiToken = sheet.getRange(API_TOKEN_CELL).getValue();
var cardIds = sheet.getRange(CARD_ID_COL).getValues().flat().filter(r=>r!="");
var params = {
"method": "GET",
"muteHttpExceptions": true,
"headers": {
"Content-Type": "application/json",
"Authorization": "Basic " + Utilities.base64Encode(username + ":" + apiToken),
"x-guru-application": "spreadsheet",
"X-Amzn-Trace-Id": "GApp=spreadsheet"
}
};
cardIds.forEach(function (cardId) {
var fullUrl = "https://api.getguru.com/api/v1/cards/"+cardId+"/comments"
var cardComments = getItAll(fullUrl, username, apiToken);
var fullUrl = "https://api.getguru.com/api/v1/cards/"+cardId+"/extended"
var response = UrlFetchApp.fetch(fullUrl, params);
var cardData = JSON.parse(response.getContentText());
var sheetLastRow = sheet.getLastRow();
var range = sheet.getRange("A" + sheetLastRow);
if (range.getValue() !== "") {
var lastRow = sheetLastRow+1;
} else {
var lastRow = range.getNextDataCell(SpreadsheetApp.Direction.UP).getRow()+1;
}
cardComments.forEach(function(comment, commentIndex) {
sheet.getRange(lastRow + commentIndex, 1).setValue(comment.dateCreated);
sheet.getRange(lastRow + commentIndex, 1 + 1).setValue(comment.content);
sheet.getRange(lastRow + commentIndex, 1 + 2).setValue(cardData.preferredPhrase);
});
});
}
So I am trying to send message to LINE Notify from Google Spreadsheets via google form responses, I already testing the API with Postman and it works, I got the Notification, however it doesn't works on the Apps Script Code. here's the error log:
function autoFillPendataanKontak(e) {
var nama = e.values[1];
var nim = e.values[2];
var bidang = e.values[3];
var file = DriveApp.getFileById('------');
var doc = DocumentApp.openById(file.getId());
var body = doc.getBody();
function sendLineNotify(messageNama, messageBidang) {
var token = ["------"];
var options = {
"method": "post",
"payload": messageNama + " telah mendaftar di Bidang " + messageBidang,
"headers": {
"Authorization": "Bearer " + token
}
};
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}
function appendTable(variabel1, variabel2){
var rangePSDI = null;
var searchElement = body.findElement(DocumentApp.ElementType.TABLE, rangePSDI);
element = searchElement.getElement();
table = element.asTable();
if (bidang == 'PSDI') {
body.replaceText('{{a}}', variabel1);
body.replaceText('{{b}}', variabel2);
var tr = table.appendTableRow();
var ukur = table.getNumRows();
ukur -= 3;
tr.appendTableCell(ukur+1);
tr.appendTableCell("{{a}}");
tr.appendTableCell("{{b}}");
} else if (bidang == 'PSDM') {
body.replaceText('{{c}}', variabel1);
body.replaceText('{{d}}', variabel2);
var tr = table.appendTableRow();
var ukur = table.getNumRows();
ukur -= 3;
tr.appendTableCell(ukur + 1);
tr.appendTableCell("{{c}}");
tr.appendTableCell("{{d}}");
}
}
appendTable(nama, nim);
sendLineNotify(nama, bidang);
doc.saveAndClose();
}
Solved the problem, I just forgot the "message=" on payload
"payload": "message=" + messageNama + " telah mendaftar di Bidang " + messageBidang,
I am trying to develop a chrome extension which parses data from the current tab and post it to a url which does processing on the data. In certain cases the page may need to be redirected so that certain get parameters are present. My popup.js can successfully do the redirect, but I need to click on the extension a second time to get it to run properly. Note: it runs properly if the page has the correct parameters. How can I adjust this so that the code reruns after the redirect and posts the new source to the specified url.
Here is my popup.js:
var url = "";
chrome.runtime.onMessage.addListener(function(request, sender) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
url = tabs[0].url;
if (url.search("[?&]view=list") == -1)
{
url = setGetParameter(url,'view','list');
chrome.tabs.update(tabs[0].id,{url:url});
process(request);
}
});
process(request);
});
function process(request) {
if (request.action == "getSource") {
message.innerText = request.source;
var data = new FormData();
data.append('source',request.source);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
message.innerText = xhttp.responseText;
}
}
xhttp.open("POST","http://127.0.0.1:5000/api/scraper",true);
xhttp.send(data);
}
}
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
function setGetParameter(url, paramName, paramValue)
{
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
return url + hash;
}
window.onload = onWindowLoad;
Take a look at webRequest.onBeforeRedirect, this event fired when a redirect is about to be executed. You can listen to this event and do your logic again.
Don't forget to declare webRequest permission along with host permissions for any hosts whose network requests you want to access in you manifest.json.
I wrote a script in JS that will retrieve the traffic source of the user and store that value in a cookie.
For all but three pages this works. If the user's landing page is for example www.example.com/example1, www.example.com/example2 or www.example.com/example3 the cookie gets stored on those pages only. I do not see see it in developer tools on chrome but when I write document.cookie I do see the cookie I created. I also see it in settings.
But if I were to navigate to another page it doesn't get stored.
It works fine on all other pages, the user enters on the landing page and the cookie stays stored during the whole session. Except on the above pages.
The hostname is the same for all pages.
Any ideas?
var source = trafficSource();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
var source = document.referrer;
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function checkCookie() {
var verifyCookie = getCookie("Traffic Source Cookie");
if (verifyCookie != null ){
//alert("there is a cookie");
return "";
}else{
setCookie("Traffic Source Cookie", source, 30);
//alert("new cookie made");
}
}
checkCookie();
var trafficSourceValue = getCookie("Traffic Source Cookie"); // delete if doesnt work
//dataLayer.push( "Cookie Traffic Source is " +getCookie("Traffic Source Cookie"));
function trafficSource(trafficType){
var trafficType;
//set traffic sources to variables
/*var sourceSearchEngine = searchEngine();
var sourceSocialNetwork = socialNetwork();
var sourcePaidSearch = paidSearch(); */
// get what kind of referrer
var trafficReferrer = document.referrer;
var trafficURL = document.URL;
if(trafficURL.indexOf("gclid") > -1) {
trafficType = paidSearch();
//alert("paidSearch google");
} else if (trafficURL.indexOf("bing") >-1 &&(trafficURL.indexOf("ppc")> -1) || (trafficURL.indexOf("cpc") >-1)){
trafficType = paidSearch();
//alert("paidSearch bing");
}
else if((trafficReferrer.indexOf("plus.url.google.com")<= 0) && trafficReferrer.indexOf("google")>-1 || trafficReferrer.indexOf("bing")>-1 || trafficReferrer.indexOf("baidu") >-1 || trafficReferrer.indexOf("yahoo") > -1 && (trafficURL.indexOf("ppc") < 0)){
trafficType = searchEngine();
//alert("searchEngine");
//(trafficReferrer.indexOf("facebook","googleplus", "twitter", "t.co/", "linkedin", "pinterest","reddit","disqus","blogspot.co.uk") >-1
} else if ((trafficReferrer.indexOf("facebook")>-1) || (trafficReferrer.indexOf("plus.url.google.com")>-1) || (trafficReferrer.indexOf("t.co/")>-1) || (trafficReferrer.indexOf("linkedin")>-1) || (trafficReferrer.indexOf("reddit")>-1) || (trafficReferrer.indexOf("disqus")>-1) || (trafficReferrer.indexOf("blogspot.co.uk")>-1) || (trafficReferrer.indexOf("t.umblr")>-1)) {
trafficType = socialNetwork();
//alert("socialNetwork");
} else if (trafficReferrer.indexOf("")>-0){
trafficType = directSource();
//alert("direct");
}else if (trafficURL.indexOf("display") >-1 || trafficURL.indexOf("Display") >-1){
trafficType = display();
//alert("display");
}else if (trafficReferrer === "" || trafficReferrer === null){
trafficType = "Direct";
}else {
//var hostnameReturn = hostname.split("www.");
var returnReferrer = document.referrer.match(/https?:\/\/([^\/]*)(?:\/|$)/i)[1].replace(/www\./, "");
// do I need this snippet
trafficType = returnReferrer + "/Referral" ;
//alert("Hostname Referral");
}
//Return the trafficType which is the function that will get source
return trafficType;
// alert("trafficType");
}
//setCookie("trafficSource",1,30)
//search engine source
function searchEngine (referrer){
var search = document.referrer;
var bing = "bing";
var google ="google";
var yahoo = "yahoo";
var ask = "ask";
var msn = "msn";
var baidu = "baidu";
var referrer;
if (search.indexOf(bing)> -1){
//alert(bing);
referrer = bing + " organic";
} else if (search.indexOf(yahoo)>-1){
// alert(bing);
referrer = yahoo + " organic";
} else if (search.indexOf(ask)>-1){
referrer = ask + " organic";
} else if (search.indexOf(msn)>-1){
// alert(bing);
referrer = msn + " organic";
} else if (search.indexOf(baidu)>-1){
// alert(baidu);
referrer = baidu + " organic";
}
else{
// alert(google);
referrer = google + " organic";
}
return referrer;
// alert("Search Engine: " + referrer);
}
//search social network
function socialNetwork (referrer){
var search = document.referrer;
var facebook ="facebook";
var twitter = "twitter";
var googlePlus = "google plus";
var googlePlus2 = "plus.url.google.com";
var pinterest ="pinterest";
var linkedin = "linkedin";
var tumblr = "t.umblr";
var reddit = "reddit";
//var beforeItsNews ="news";
var disquis = "disqus";
var blogger = "blogspot.co.uk";
//var StumbleUpon = "StumbleUpon";
var referrer;
if(search.indexOf(facebook)> -1){
// alert(facebook);
referrer = "Social/ " + facebook;
}else if (search.indexOf(twitter)> -1 || search.indexOf("t.co/") >-1){
// alert(twitter);
referrer = "Social/ "+ twitter;
}else if (search.indexOf(pinterest)> -1){
//alert(pinterest);
referrer = "Social/ "+ pinterest;
}else if (search.indexOf(linkedin) >- 1){
//alert(linkedin);
referrer = linkedin;
}else if (search.indexOf(googlePlus) >-1 || search.indexOf(googlePlus2) >-1){
// alert(googlePlus);
referrer = "Social/ "+ googlePlus;
}else if (search.indexOf(tumblr) >-1){
// alert(googlePlus);
referrer ="Social/ "+ "tumblr";
}else if (search.indexOf(reddit) >-1){
// alert(googlePlus);
referrer = "Social/ " + reddit;
}else if (search.indexOf(disquis) >-1){
//alert(disquis);
referrer = "Social/ "+ disquis;
}else if (search.indexOf(blogger) >-1){
blogger ="Blogger";
//alert(blogger);
referrer = "Social/ "+ blogger;
}else{
// alert(document.referrer);
referrer = "Referral: " + document.referrer;
// alert("Check Cookie - Referrer");
}
return referrer;
// alert("Social Media Network: " + referrer)
}
// search for paid search
function paidSearch(referrer){
var paidCampaign = document.URL;
var campaignReferrer = document.referrer;
var referrer;
var googleAd = "gclid";
var justGoogle = "google";
var justBing = "ppc";
var bingAd = "Bing";
if (paidCampaign.indexOf(googleAd) >- 1 || campaignReferrer.indexOf(justGoogle) >-1){
googleAd = "Google/CPC ";
// alert(googleAd);
//referrer = paidCampaign; < original code but trying the code on the bottom>
referrer = googleAd;
// alert(referrer);
}
if (paidCampaign.indexOf(bingAd)>- 1 || paidCampaign.indexOf(justBing) >-1){
bingAd = "Bing/CPC ";
//alert(bingAd);
referrer = bingAd ;
}
return referrer;
// alert("The paid ad is: " + googleAd);
}
function directSource(referrer){
var directVistor = document.referrer;
if(directVistor ==="" || directVistor === null ){
referrer = "Direct";
//alert("Direct");
}
return referrer;
}
function display(referrer){
var displayURL = document.URL;
var referrer;
if(displayURL.indexOf("display") >- 1 || displayURL.indexOf("Display")>-1){
var returnDisplay = window.location.search.substring(1);
referrer = "Display: " + returnDisplay;
//alert(referrer);
return referrer;
}
}
// function urlSpilt(url){
// // return utm_source and utm_medium if iti has it.
// var url;
// var getURL = document.URL;
// //var testURL = "http://www.franciscoignacioquintana.com/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName";
// var getURL = getURL.split("utm_source");
// getURL = getURL[1].split("utm_source");
// url = getURL;
// return url;
// }
//http://www.currencies.co.uk/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName
function getQueryParam(par){
//var strURL = document.URL;#
var strURL = document.referrer;
var regParam = new RegExp("(?:\\?|&)" + par + "=([^&$]*)", "i");
var resExp = strURL.match(regParam);
if((typeof resExp == "object") && resExp && (resExp.length > 1)){
return resExp[1];
}
else{
return "";
}
}
//var hostname = window.location.hostname;
//var hostnameReturn = hostname.split("www.");
//var hostname2 = hostname.slice(4);
I am trying to make an autosave that can be dropped into any of my forms and be "self aware" of the content in order to simulate an actual save. In addition, I want it to be able to notify the user in the event of multiple failures of the autosave. The following is the come I have come up with, but I keep getting readyState = 4 and status = 500 as a result of my XMLHttpRequest.send(). When I "normally" click save with the form, the save works perfectly fine, but this code just doesn't seem to pass the data over correctly. Every page that has this code has a setTimeout(autosave,5000) to initialize the code. Can someone point me in the right direction of what I'm doing wrong? I'm new to XMLHttpRequest objects.
For what I can tell, last_params gets "sent" with the correct data, but when I get it via the request() (using classic ASP on the other end), the value is "" (blank). I'm thinking I have an order of execution problem, I just don't know what or where.
Quick footnote: I know that there are 'similar' functions with jQuery and other frameworks, but I do not feel comfortable enough with them yet. I want to start with something "simple".
var last_params = "";
var autosave_time = 61000;
var autosave_fail_check = 5;
var max_autosave_fail_check = 5;
var response_text = "";
function autosave() {
var autosave_button_name = "save_button";
var form_action = document.getElementById("formS").action;
var form_data = document.getElementById("formS");
var all_inputs = form_data.getElementsByTagName("input");
var all_textareas = form_data.getElementsByTagName("textarea");
var params = "";
// Check all inputs for data
for (var i = 0; i < all_inputs.length; i++) {
var current_item = all_inputs[i];
if (current_item.type != "button" && current_item.type != "submit") {
if (current_item.type != "checkbox") {
params += current_item.name + "=" + current_item.value + "&";
} else {
params += current_item.name + "=" + current_item.checked + "&";
}
}
}
// check all textareas for data
for (var i = 0; i < all_textareas.length; i++) {
var current_item = all_textareas[i];
params += current_item.name + "=" + current_item.value + "&";
}
params += "autosave=1";
if (params == last_params) {
setTimeout(autosave, autosave_time);
return;
} else {
last_params = params;
}
// Setup time
var time = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
time = hours + ":" + minutes + ":" + seconds;
if(hours > 11){
time = time + "PM";
} else {
time = time + "AM";
}
var status = "[]";
// **************************************************
var http;
try {
// Gecko-based browsers, Safari, and Opera.
http = new XMLHttpRequest();
} catch(e) {
try {
// For Internet Explorer.
http = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
// Browser supports Javascript but not XMLHttpRequest.
document.getElementById(autosave_button_name).value = "Autosave NOT Available";
http = false;
}
}
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
autosave_fail_check = max_autosave_fail_check; // reset the fail check
}
status = " [" + http.readyState + " / " + http.status + "] ";
}
if (autosave_fail_check <= 0) {
if (autosave_fail_check == 0) {
document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
//alert("Autosave has FAILED! Please check your connection!");
}
autosave_fail_check = -1;
} else {
autosave_fail_check--;
}
var url = form_action;
http.open("POST", url, true); // async set to false to prevent moving on without saving
http.setRequestHeader("Content-type", "multipart/form-data");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(last_params);
response_text = http.responseText;
if (autosave_fail_check >= 0) {
document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
} else {
autosave_fail_check = -1;
}
setTimeout(autosave, autosave_time);
} // end function autosave()