non-cacheable reported in my chrome extension, how to make "cacheable"? - javascript

I'm learning to write a chrome extension. I want to inject a real-time time-stamp in current webpage.
I've already finished manifest.json, and html file as background. This html file will call a js file to get current time and display it.
While I do audits in chrome, it says:
The following resources are explicitly non-cacheable. Consider making them cacheable if possible:clock.html, ccc.js, cbd.js.
Here are contents of these three files:
(1) clock.html
<html>
<head>
<script src="ccc.js"></script>
</head>
<font size="7" color='red'>
<body>
<script src="cbd.js"></script>
<div id="showme"></div>
</body>
</font>
</html>
(2) ccc.js
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes()
var s=today.getSeconds();
var w=today.getMilliseconds()%1000;
h=checkTime(h);
m=checkTime(m);
s=checkTime(s);
w=checkMS(w);
document.getElementById('showme').innerHTML=h+":"+m+":"+s+":"+w;
t=setTimeout('startTime()',1);
}
function checkTime(i)
{
if (i<10)
{i="0" + i;}
return i;
}
function checkMS(i)
{
if((i>9)&&(i<100))
i="0" + i;
else if(i<10)
i="00" + i;
else
{}
return i;
}
(3)cbd.js:
window.addEventListener("load", startTime);
How to make them cacheable...?
Thanks!

Thanks guys, problem solved.
I changed my method, just inject the java script, and it finally works.

Related

Loading text from a txt file depending on day of week

I am using this which loads images depending on day of the week, but I also would like to show text and load it from a file, too. I like to use it as todays menu, so the cook uploads text files, like monday.txt tuesday.txt, and does not need to mess up with coding.
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<META HTTP-EQUIV="refresh" CONTENT="60">
<title>LOUNAS</title>
<style type="text/css">
body {
overflow:hidden;
}
</style>
<script type="text/javascript"><!--
var imlocation = "";
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(7);
image[0] = 'sunday.jpg';
image[1] = 'monday.jpg';
image[2] = 'tuesday.jpg';
image[3] = 'wednsday.jpg';
image[4] = 'thursday.jpg';
image[5] = 'friday.jpg';
image[6] = 'saturday.jpg';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.write('<img src="' + imlocation + image[imagenumber] + '"> style="width:100%;height:100%;" border="0" /');
//--></script></head>
<body bgcolor="#000000">
</body>
</html>
You need to use AJAX request in order to read files from the server.
(If your intention is to display the data to client and not self-display site)
You'll need a server and back-end language like PHP, and then you'll need to make an AJAX request to server depend on the day of the week (meaning which url?) and then display the data.
Second, about what you did, using document.write it's not best way, becuase it clear the page after using and all the data that you had will gone (meaning HTML), and also create element this way dosen't work good in all browsers , you should use createElement instead.
Also, you can use CSS to give style to that element instead of doing it via JavaScript

My javascript application I created only works once and then can't be replicated unless I delete the file

I hope I'm not asking a "duhish" question with what I'm asking but I do need some clarification on what's going on in the "background". I created a simple clock exercise for myself this weekend. It works, it shows up on my browser and shows the current time just like I want it to. That said, when I try to create it again with a different HTML file and Javascript file.... it doesn't work again. It shows up in the original file I created but on the same file that has the same code... It doesn't show the timer.
Here's the HTML I wrote down in the original
<html>
<head>
<title>Kenneth's clock</title>
<meta charset="UTF-8">
<link rel='stylesheet' type='text/css' href=''>
<script src='clock.js'></script>
</head>
<body>
<p id ='clock'></p>
</body>
</html>
Then the Javascript.
function getTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('clock').innerHTML = h + ":" + m + ":" + s;
setTimeout('getTime()', 1000);
function checkTime(time) {
if(time<10) {
time = "0" + time;
}
return time;
}
}
window.onload = function() {
getTime();
}
Imagine if I recreated that entire thing again and I changed the id on the new HTML file to digitalclock. I make the new code in javascript to getElementById('digitalclock') and viola.. new exercise to learn basic javascript....
For some reason, it doesn't work. What's going on in the backend to make it so that I can't get it to work?

Javascript not rendering - Blank head

There's something wrong with my script, it doesn't render the JS correctly. I tried to pinpoint the problem but cannot find any typo. If i load the page, the tag is blank, making all css & other JS disabled. But suprisingly the data is loader correctly. If i remove the script, everything went to normal.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "Customers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
$("#middle").ready( function () {
document.write("<ul class='product'>");
for (var i = 0; i < Customers.children.length; i++)
{
var dul = "wawa"+[i];
//document.getElementById(dul).addEventListener('click', storeData, false);
var Customer = Customers.children[i];
// Access each of the data values.
var Pic = Customer.getElementsByTagName("pic");
var Name = Customer.getElementsByTagName("name");
var Age = Customer.getElementsByTagName("tipe");
var sex = Customer.getElementsByTagName("country");
var checked = window.localStorage.getItem("selected"+i);
// Write the data to the page.
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
document.write(Name[0].textContent.toString());
document.write("</a><div class='age'>");
document.write(Age[0].textContent.toString());
document.write("</div><div class='sex'>");
document.write(sex[0].textContent.toString());
document.write("</div><div class='cex'>");
document.write("<input name='checkbox' type='checkbox' id='wawa_"+i+"'");
if (!checked) {
document.write(" onClick='cbChanged(this, "+i+")'");
} else {
document.write("checked onClick='cbChanged(this, "+i+")'");
}
document.write("></div></li>");
}
document.write("</ul>");
});
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
</script>
</head>
<body>
<div class="container">
<div class="content" id="middle">
</div>
<div class="content" id="footer">
</div>
</div>
</body>
</html>
Ok here's the full source.
You don't close the HTML img tag right
Change
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write("'.jpg><a href='display.html?id="+i+"'>");
// ^ this quote
To
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
// ^ should be here
If you open the developer console you can usually see where errors like this take place. It will also output and javascript errors that you come across so it will make that part a whole lot easier. Do you have any errors in your console?
The dev consoles are:
Chrome: It is built it.
Firefox: Firebug
Safari: It's built it
EDIT:
Don't do var functionName = function() {..} unless you know about how hoisting works. This is contributing to you problem so change
cbChanged = function(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
To
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
Without the above changes the function cbChanged is not hoisted. So if you call it before it is reached you will get an error.
There are several other things that stand out to me on this. You might want to spend some more time on your javascript fundamentals. Read up on why document.write is a bad thing. Try removing parts of the script to narrow down what is causing the problem. It would have made this easier to fix if you had made a fiddle.

Load script only for returning USER - once!

I need a script which will load another script only for returning user!
The script which will need to load this script
<a href="http://www.w3.org/" >W3C</a>
I have a script which loads a popup only for new customers:
<SCRIPT LANGUAGE="JavaScript">
<!-- Script courtesy of http://www.web-source.net - Your Guide to Professional Web Site Design and Development
function GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0) break;
}
return null;
}
var visit=GetCookie("COOKIE1");
if (visit==null){
var expire=new Date();
window.name = "thiswin";
newwin=open("yourpagename.html", "dispwin",
"width=450,height=455,scrollbars=yes,menubar=no");
expire=new Date(expire.getTime()+7776000000);
document.cookie="COOKIE1=here; expires="+expire;
}
// -->
</SCRIPT>
Yet I need the script only to load once for the returning customers every 1 day
thanks again
7776000000 equals 90 days.
Make the cookie expire every 24 hours [86400000] and you get once a day.

How can I change a JavaScript variable using Greasemonkey?

This is the page that I am trying to modify, I want to bypass the countdown timer, how should I write the script?
Is there a way that I can change the variable document.licenseform.btnSubmit.disabled to yes using Greasemonkey?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>dsfsdf</title>
</head>
<body>
<form name="licenseform" method="post" action="">
<input name="btnSubmit" type="button" value="我同意">
</form>
<SCRIPT language=javascript type=text/javascript>
<!--
var secs = 9;
var wait = secs * 1000;
document.licenseform.btnSubmit.value = "我同意 [" + secs + "]";
document.licenseform.btnSubmit.disabled = true;
for(i = 1; i <= secs; i++)
{
window.setTimeout("Update(" + i + ")", i * 1000);
//这一句很关键,记得参数写法为("update("+i+")",i*1000)
}
window.setTimeout("Timer()", wait);
function Update(num)
{
if(num != secs)
{
printnr = (wait / 1000) - num;
document.licenseform.btnSubmit.value = "我同意 [" + printnr + "]";
}
}
function Timer()
{
document.licenseform.btnSubmit.disabled = false;
document.licenseform.btnSubmit.value = " 我同意 ";
}
-->
</SCRIPT>
</td>
<!--网页中部中栏代码结束-->
</body>
</html>
A more secure alternative to using unsafeWindow is to inject code into the document. The code that you inject will run in the same context as the page code, so it will have direct access to all of the variables there. But it will not have access to variables or functions in other parts of your user script code.
Another benefit of injecting code is that a user script written that way will work in Chrome as well as in Firefox. Chrome does not support unsafeWindow at all.
My favorite way to inject code is to write a function, then to use this reusable code to get back the source code for the function:
// Inject function so that in will run in the same context as other
// scripts on the page.
function inject(func) {
var source = func.toString();
var script = document.createElement('script');
// Put parenthesis after source so that it will be invoked.
script.innerHTML = "("+ source +")()";
document.body.appendChild(script);
}
To toggle btnSubmit you could write a script like this:
function enableBtnSubmit() {
document.licenseform.btnSubmit.disabled = false;
document.licenseform.btnSubmit.value = " 我同意 ";
// Or just invoke Timer()
}
function inject(func) {
var source = func.toString();
var script = document.createElement('script');
script.innerHTML = "("+ source +")()";
document.body.appendChild(script);
}
inject(enableBtnSubmit);
Remember that when you use the serialized form of a function in this way normal closure scope will not work. The function that you inject will not have access to variables in your script unless they are defined inside that function.
try calling the Timer() function since its what you want to happen anyway:
unsafeWindow.Timer();
while you are at it, change the Update function to do nothing:
unsafeWindow.update = function(){}
This is possible. The short answer is you can use the object unsafeWindow, for instance
unsafeWindow.document.licenseform.btnSubmit.disabled = true;
However it is not recomemended to do so, because it is unsecure. More information about this here:
http://wiki.greasespot.net/UnsafeWindow
Disregard anything said about "insecure", because script->document write operation IS perfectly secure.
unsafeWindow.document.licenseform.btnSubmit.disabled = false;
(Use mkoryak's method to suppress timeout callback)
That given form contains nothing but timeout, so you might want to bypass it completely:
// this example is INSECURE
unsafeWindow.document.licenseform.submit();
See?

Categories

Resources