How can i excute script New page in chrome extension? - javascript

I make chrome extension.
this program read now page and anlysis it, go to next page.
I already made read and goto next page. but there a problem.
read now page and move next page is perfect. but next page, read function isn't work.
I click read button on first page, read it. but move next and read, not work.
i see callback function get undefined data.
below is my code.
function matching(user) {
JustFIDsFromPage();
}
function JustFindIDsFromPage() {
//read and find Data
chrome.tabs.executeScript({
code: "var ids = [];var names = document.querySelector('.gallery').children;for(var i=0;i<names.length;i++){var tmp = names[i].innerHTML;var id = tmp.substring(11+tmp.search('/galleries/'),tmp.search('.html'));ids.push(id)} ids"
}, callbackJustFindIDsFromPage);
}
function callbackJustFindIDsFromPage(count) {
//save get datas.
var idList = count.toString().split(',');
for (var i = 0; i < idList.length; i++) {
document.querySelector('#result').innerText += idList[i] + "\n";
}
//go to next page.
chrome.tabs.executeScript({
code: "var page = document.querySelector('.page').firstElementChild.children; var end=0; var inhtml = page[1].innerHTML;var intext = page[1].innerText; if(inhtml == intext){var link = page[2].innerHTML; var url = link.substring(9, 20); end=1; window.location.href = url; } end;"
}, callbackGoNextPage);
}
function callbackGoNextPage(nextFlag) {
if (nextFlag == 1) {
JustFindIDsFromPage();
}
}
I guess this.
chrome.tabs.executeScript just excute on 'first' open page.
I don't know what is real. please help me!

this code will work for you.
chrome.tabs.getSelected(null, function (tabss) {
tabid = tabss.TAB_ID_NONE;
});
chrome.tabs.update(tabid, { url: url, active: true }, function (tab1) {
var listener = function (tabId, changeInfo, tab) {
if (tabId == tab1.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
//your code
}
}
chrome.tabs.onUpdated.addListener(listener);
});

Related

Cannot communicate between captivate html and parent html

I have a published captivate html file that is loaded into an iframe of another html. I cannot communicate between the two, not even with localStorage. Can anyone tell me what I'm missing?
Parent html
var everythingLoaded = setInterval(function () {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(everythingLoaded);
init();
}
}, 10);
function init() {
ScormProcessInitialize();
var studentID = ScormProcessGetValue("cmi.core.student_id");
var student_name = ScormProcessGetValue ("cmi.core.student_name");
var nameArraya = student_name.split(" ");
var nameArrayb = nameArraya[1].split(",");
var studentNumber = nameArrayb[0];
ScormProcessSetValue("cmi.core.lesson_status", "incomplete");
localStorage.setItem("_studentNumber", studentNumber);
alert("Student Number: " + studentNumber + " Student Mame: " + student_name);
setTimeout(function () {
document.getElementById("iFrame_a").innerHTML = "<iframe name='iframe_1' id='frame_1' src='//somepath.com/sandbox/somecourse/index.html' frameborder='0' width='1000px' height='605px'></iframe>";
}, 250);
}
function sendComplete() {
alert("Send from index start!");
ScormProcessSetValue("cmi.core.lesson_status", "completed");
alert("send status: Completed");
}
window.onbeforeunload = function (){
cpInfoCurrentSlide = localStorage.getItem("_cpInfoCurrentSlide")
alert(cpInfoCurrentSlide);
if(cpInfoCurrentSlide >= 40)
{
alert("onbeforeunload called: " + cpInfoCurrentSlide )
ScormProcessSetValue("cmi.core.lesson_status", "completed");
}
}
iframe code snippet
localStorage.setItem("_cpInfoCurrentSlide", cpInfoCurrentSlide);
I believe your problem is with onbeforeunload. As I remember captivate packages clobber any functions associated with onbeforeunload in the parent frame when they load.
Try this instead, override your SCORM api setvalue method:
var oldLMSSetValue = window.API.LMSSetValue;
window.API.LMSSetValue = function(key, value){
if(key === 'cmi.core.lesson_status' && value === 'completed'){
//do your stuff here
cpInfoCurrentSlide = localStorage.getItem("_cpInfoCurrentSlide")
alert(cpInfoCurrentSlide);
}
//call the original scorm api function so that it runs as expected.
oldLMSSetValue(key,value);
};
edit: this code would go in the parent window, not the iframe.

How do I fire a function immediately after another function is finished?

I have the following code:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
window.setInterval(function(){
refreshChat();
}, 2000);
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});
</script>
Right now, the refreshChat function calls an ajax script every 2 seconds. When you have entered a message and press enter, it calls a different ajax script. What I would like it to do, is call both functions at the same time. So the script calls the sendMessage function first and refreshes afterwards.
How can I do this? I have already tried changing it to:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();refreshChat();
}
});
</script>
But this only enters the message first, and it only refreshes on the second keypress (enter). I would like to thank everybody beforehand on helping me out.
This is actually an illusion. Both functions are being called, but the chat window is refreshing before the chat message is able to save them.
To fix this, you should refresh the chat window only once the new message has been successfully saved:
function refreshChat() {
// Removed for brevity
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
// Now, this will only be called once the ajax is complete
refreshChat();
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
// I removed the refreshChat() call from here and moved it
// into the $.get() callback above ^^
}
});
As you can see, I moved your refreshChat() method to now be called from within the jQuery $.get() callback.
Have you tried using callbacks, that may be what you need?
Here is a link for reference.
http://www.impressivewebs.com/callback-functions-javascript/
MY WORKING AWNSER
Considering for what i asked, i have marked Wes Foster's awnser as correct. What made it work for me is also applying a promises after the get function. This way, the ajax script get's called twice as needed. I hope it will help someone in the future. (Look at me... travelling through time...). You will find my code underneath:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
refreshChat();
}).done(refreshChat);
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});

Console.log Internet explorer 8 particular case [duplicate]

This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.

Page loading is gradually getting slower using jQuery script

I'm using this jQuery script to show search results. Everything works fine, but when search results have more than one page and I'm browsing pages via paging then every page loading is gradually getting slower. Usually first cca 10 pages loads I get quickly, but next are getting avoiding loading delay. Whole website get frozen for a little while (also loader image), but browser is not yet. What should be the problem?
function editResults(def) {
$('.searchResults').html('<p class=\'loader\'><img src=\'images/loader.gif\' /></p>');
var url = def;
var url = url + "&categories=";
// Parse Categories
$('input[name=chCat[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&sizes=";
// Parse Sizes
$('input[name=chSize[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&prices=";
// Parse Prices
$('input[name=chPrice[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
$('.searchResults').load('results.php'+url);
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
}
$(document).ready(function(){
editResults("?page=1");
// Check All Categories
$('input[name=chCat[0]]').click(function() {
check_status = $('input[name=chCat[0]]').attr("checked");
$('input[name=chCat[]]').each(function() {
this.checked = check_status;
});
});
// Check All Sizes
$('input[name=chSize[0]]').click(function() {
check_status = $('input[name=chSize[0]]').attr("checked");
$('input[name=chSize[]]').each(function() {
this.checked = check_status;
});
});
// Edit Results
$('.checkbox').change(function() {
editResults("?page=1");
});
// Change Type
$(".sort").change(function() {
editResults("?page=1&sort="+$(this).val());
});
});
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
just a wild guess but... wouldn't this piece of code add a new event handler to the click event instead reaplacing the old one with a new one? causing the click to call all the once registered handlers.
you should make the event binding just once
var global_var = '1';
function editResults(def) {
// all your code
global_var = 2; // what ever page goes next
};
$(document).ready(function() {
// all your code ...
$('.pageLinks').live("click", function() {
var page = global_var;
editResults("?page="+page);
});
});

How to submit a form using PhantomJS

I'm trying to use phantomJS (what an awesome tool btw!) to submit a form for a page that I have login credentials for, and then output the content of the destination page to stdout. I'm able to access the form and set its values successfully using phantom, but I'm not quite sure what the right syntax is to submit the form and output the content of the subsequent page. What I have so far is:
var page = new WebPage();
var url = phantom.args[0];
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
console.log(page.evaluate(function () {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin#somedomain.example";
arr[i].elements["password"].value="mypassword";
// This part doesn't seem to work. It returns the content
// of the current page, not the content of the page after
// the submit has been executed. Am I correctly instrumenting
// the submit in Phantom?
arr[i].submit();
return document.querySelectorAll('html')[0].outerHTML;
}
}
return "failed :-(";
}));
}
phantom.exit();
}
I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.example/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.
CasperJS
Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.
(Thanks to commenter Mr. M!)
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.example/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
As it was mentioned above CasperJS is the best tool to fill and send forms.
Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});

Categories