Injection of contenscript into a page not working? - javascript

I injected contentscript into a page by :
//this is in background.js
chrome.tabs.executeScript(null, {"file": "contentscript.js"});
Then to check if it inserted well or not I modified an element on the page, but no changes made.
Did I inject it properly?
Here are my files :
background.js:
//injecting contentscript here
     chrome.tabs.executeScript(null, {"file": "contentscript.js"});
//receiving end
var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.method == 'setTitle')
title = message.title;
else if(message.method == 'getTitle')
sendResponse(title);
});
contentscript.js:
<script>
var table = document.getElementsByClassName("collapse")[0];
var marks = new Array();
for(var i=0;i<8;i++)
marks[i] = table.children[0].children[i+1].children[5].innerHTML;
var total=0;
for(var i=0;i<8;i++)
total += Number(marks[i]);
//code to send the data to background.js
var fromDOM = total;
chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});
</script>
popup.js:
var total= 0,percentage = 0;
chrome.runtime.sendMessage({method:'getTitle'}, function(response){
$('.total').text(response);
percentage = total/7.25;
$('.percentage').text(percentage);
});
Why is this not working? Any changes or errors?
This is how my popup.html is looking :

Related

How keep the Status keep appearing on JavaScript function to HTML

This is a continuation of previous question I made in this forum.
I made some changes in the code by adding else condition. What I'm trying to work out is to show the current status as the page loads. the current code shows the status only if the button get clicked.
How can I get the current status appear as the page loads and the status get updated when button get clicked.
CODE.GS
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index');
}
function checkStatus(notify) {
var employee = "John Peter";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("MAIN");
var data = mainSheet.getDataRange().getValues();
for (var j = 0; j < data.length; j++){
var row = data[j];
var mainSheet2 = row[4];
var mainSheet3 = row[0];
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
if (status == true){
var notify = employee +" You Are In"
return notify;
}
else{
var status = (mainSheet2 =="OUT" && mainSheet3 == employee) ;
if (status == true){
var notify2 = employee +" You Are Out"
return notify2;
}
}
}
}
Index.html
<body>
<div>
<button onclick="onStatus()">Check Status</button>
<font color='Green' id="status" onbeforeprint="onStatus" ></font>
</div>
<script>
function onStatus() {
google.script.run.withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
.checkStatus(); // Call the backend function
}
function updateStatus(notify) {
document.getElementById('status').innerHTML= notify;
}
</script>
</body>
You can invoke this function at page load like below. Add this script at then end, just before your body tag ends.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(updateStatus)
.checkStatus();
});
</script>

JavaScript Chrome printing multiple screens

problem in Chrome printing multiple screens
the code below is designed to load records from a list of students and print the resulting screen for each student.
this works fine in browsers other than Chrome
Chrome does not display each students record result and thus prints multiple copies of just one student.
When the script finishes the last student record in the list is displayed so we know that the form request is being made successfully. It appears Chrome is not waiting for the form request to load or that it doesn't update the screen before getting to the print command.
function printAll() {
var stdsObj = document.getElementById('stds');
for ( var i = 0; i < stdsObj.options.length; i++ ) {
showRec(i)
printIframe("main")
}
}
function showRec(selRec) {
var recID = '';
var recName = '';
var recNum = '';
var stdsObj = document.getElementById('stds');
recID = stdsObj.options[selRec].value;
recName = stdsObj.options[selRec].text;
recNum = selRec +1;
document.getElementById('recID').value = recID;
document.getElementById('recName').value = recName;
document.getElementById('recNum').value = recNum;
document.getElementById('noCacheRec').value = Math.random();
document.recList.submit()
}
function printIframe(id) {
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printMe();
return false;
}
The form recList loads data into iframe "main"
<form id="recList" name="recList" action="ru_cse_view.pl" target="main">
printMe is a function in the iframe "main" that prints the iframe
function printMe() {
window.print()
}

AJAX - reload page if JSON has changed

I cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...

How to return success after running a script

I'm really new to both Perl and Ajax and I was wondering how do I return a message for ajax to know if a script ran successfully and run a success script after knowing the perl script was successful.
On my main html page I have an ajax script like this:
$(document).on('click', '.archive-button', function(){
var notice_id = $(this).data('notice_id');
var archiveaddress = '/user/notices/archivenotice/' + notice_id;
$.post(archiveaddress, {notice_id: notice_id});
});
which send its to the archivenotice.html page which runs a Perl script which just marks the time the notice was read.
my $update_needed = 0;
unless ($notice->read_on()) {
$notice->read_on(scalar localtime);
$update_needed = 1;
}
What should I add to the Perl script on the archivenotice.html pages so that the ajax on my main html page knows the script ran successfully and initiate another script called "successful"
Open a channel of communication between your main.html page and archivenotice Perl script.
main.html
$(document).on('click', '.archive-button', function(){
var notice_id = $(this).data('notice_id');
var archiveaddress = '/user/notices/archivenotice/' + notice_id;
$.post(archiveaddress, {notice_id: notice_id}, function( data ) {
if ( data ) { alert('Update needed!'); }
else { alert('Update not needed.'); }
});
});
archivenotice
my $update_needed = 0;
unless ($notice->read_on()) {
$notice->read_on(scalar localtime);
$update_needed = 1;
}
print "Content-type: text/plain\n\n";
print $update_needed;
exit;
Try this:
$(document).on('click', '.archive-button', function(){
var notice_id = $(this).data('notice_id');
var archiveaddress = '/user/notices/archivenotice/' + notice_id;
$.post(archiveaddress, {notice_id: notice_id}).done(function() {
alert( "update success" );
});
});

Chrome extension : Stuck at injecting script won't execute js

I am trying to build a chrome extension. Which would do some search on the page and post the results to the extensions.
I am having a hard time running this. Whenever I try to run the extension it is just stuck on Injecting Script.
my re.js
function printDetails(document_r) {
var test = document_r.body;
var text = test.innerText;
var delim="^^ validatedCache :";
var endlim="</site>";
var idx = text.indexOf(delim);
var endInd=text.indexOf(endlim);
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var regexg = new RegExp(regex,"g");
var matches = [];
while (match = regexg.exec(text.substring(idx+delim.length,endInd))) matches.push("Account Name::::::"+match[1]);
return matches;
}
chrome.extension.sendMessage({
action: "getSource",
source: "\n\n\n DETAILS>>>>>\n\n"+printDetails(document)
});
selection.js
chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "re.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.extension.lastError.message;
}
});
}
window.onload = onWindowLoad;
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='selection.js'></script>
</head>
<body style="background-image:url(12.png);width:400px; border: 2px solid black;background-color:white;">
<div id='message'>Injecting Script....</div>
</body>
</html>
I know there is some problem with these 2 lines only.
var test = document_r.body;
var text = test.innerText;
What I wan't is to extract the webpage ( contents ) into a string which I am hopefully doing by the above two lines of code.
Then do some string manipulation on the code.If I run directly this code in a console with a dummy string . I can execute it so figure something is wrong with these two lines.
My extension is stuck on " Injecting Script..."
Some help would be appreciated.
PS:yes I was able to run it earlier with the same code but somehow it doesn't run now.

Categories

Resources