2 popup pages from the same popup.js of a chrome extention - javascript

I am trying to open a new popup page after getting a result from the linked server, the alert does show correct values also the newpopup.html page does open, but it is empty, I am trying to display the result values in this newpopup.html page and eventually open the options.html page from there.
the request of result gets sent after clicking on a button on the first popup
popup.js
var values;
$(function () {
$('#keywordsubmit').click(function () {
$('#loadingDiv').show();
var search_topic = "test";
if (search_topic) {
chrome.runtime.sendMessage(
{ topic: search_topic },
function (response) {
result = response.farewell;
if ("raw" in result) { /** will return true if exist */
console.log('Exist!');
window.open(result.summary, '_newtab');
}
var pricesresult = result
values = result;
console.log('Passed0!');
nameofproduct = result.ProductName
console.log(nameofproduct);
console.log('Passed1!');
alert(pricesresult.Price + " " + pricesresult.ShopName);
if("Image" in result){
chrome.storage.local.set({nameofproduct: result }, function () {
console.log('Value is set');
});
window.location.href = "newpopup.html";}
});
}
$('#keyword').val('');
});
});
var img = document.createElement("img");
img.src = values.Image;
var src = document.getElementById("header");
src.appendChild(img);
var output = document.getElementById('output');
output.innerHTML = values.Price;
newpopup.html
<!DOCTYPE html>
<html>
<head>
<title>Price Comparator</title>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<h1>Price results</h1>
<div id="output"></div>
<div id="header"></div>
<div id="slideContainer"></div>
</body>
<script src="popup.js">
</script>
</html>

Related

How to take the console output of html file into phantomjs

I am running qunit Test using html file in one file and that html file i am running from phantom js.
When I am running html file through browser i am getting output in console but when i am trying to run using phantom js i am not getting the console output in another js file from where i am calling html file.
I am providing both Files:
HTML File :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JUnit reporter for QUnit</title>
<link rel="stylesheet" href="qunit.css">
<script src="qunit.js"></script>
<script>
QUnit.config.reorder = false;
</script>
<script src="qunit-reporter-junit.js"></script>
<script src=" http://requirejs.org/docs/release/2.2.0/minified/require.js"></script>
<script>
QUnit.jUnitDone(function(data) {
var console = window.console;
if (console) {
console.log(data.xml);
}
});
</script>
<script src="qunit-reporter-junit.test.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>
Js file :
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();
if (system.args.length === 1) {
console.log('Pass the path/to/testfile.js as argument to run the test.');
phantom.exit();
} else {
var url = "file:///C:/Users/Admin/Desktop/js/index.html"; // e.g. 'test/unit/tests.html'
console.log("Opening " + url);
}
page.open(url, function (status) {
console.log("Status: " + status);
if (status === "success") {
setTimeout(function () {
var path = 'results.xml';
var output = page.evaluate(function () {
// wants to take console output from html page
.....................................?
});
fs.write(path, output, 'w');
console.log("Wrote JUnit style output of QUnit tests into " + path);
console.log("Tests finished. Exiting.");
phantom.exit();
}, 3000);
} else {
console.log("Failure opening" + url + ". Exiting.");
phantom.exit();
}
});
can anyone suggest me how to take the console output from html file ?
Thanks In Advance.
If your test is similar to this example then to get test results you should request the contents of #qunit-testresult element.
var output = page.evaluate(function(){
return document.getElementById("qunit-testresult").innerText
});

Phantomjs evaluate does not show change to DOM

This is my html file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Script-Type" content="text/javascript"/>
</head>
<body>
<label for=payload>Payload</label><br>
<textarea id="editor" cols=100 rows=30></textarea><br>
</body>
And the phantomjs script is:
var bodyParser = require('body-parser'),
phantom = require('phantom');
var bk = {"abc":"def"};
//Create Phantom session
var _phSession;
var _page;
var log = console.log;
var config = { logger: { warn:log, info:log, error:log } };
phantom.create([], config).then(function(_session) {
if (_session) {
console.log('Phantom session created');
_phSession = _session;
return _phSession.createPage();
}
})
.then(function(page) {
_page = page;
_page.property('onConsoleMessage', function(msg) {
console.log(msg);
});
_page.property('onLoadStarted', function() {
console.log("load started");
});
_page.property('onLoadFinished', function() {
console.log("load finished");
});
return _page.open("http://myserver/my.html");
})
.then(function(status) {
console.log('Open status:' + status);
if (status != 'success') return;
_page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js')
.then(function() {
//set the new bkstore
_page.evaluate(function(bk) {
jQuery('#editor').val(JSON.stringify(bk));
return jQuery('#editor').val();
}, bkstore)
.then(function(res) {
console.log('Return from set:' + res);
})
});
setTimeout(function() {
_page.evaluate(function() {
console.log('============== EVALUATE AFTER LOADED ===================');
//return jQuery('#editor').val();
return jQuery('body').html();
})
.then(function(res) {
console.log('html:' + res);
});
}, 1000);
After I set the #editor content with bk, I get back the value I set.
In the block of setTimeout, if I try to get the content of #editor again, I still get back the value of bk.
But I get the html of the body tag, I don't see the value of bk in the #editor.
Anyone knows what the problem is?

Extract table as JSON object

I have a code which parses a website. Now I need to extract a specific table from the webpage. My code is as follows:
<html>
<head>
<title>Pricing </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script>
//$(function(){
function requestCrossDomain(site, callback) {
if (!site) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}
}
//$('#test').click(function(){
var url = 'https://www.emcsg.com/marketdata/priceinformation';
requestCrossDomain(url, 'someFunction');
function someFunction(results){
console.log(results);
$('#loadedContent').css("display","").html(results);
}
</script>
</head>
<body>
<br><br>
<div id="result"></div>
<div id="loadedContent"></div>
</body>
</html>
The webpage that is parsed is https://www.emcsg.com/marketdata/priceinformation
The webpage has a few tables, but I need to extract a specific table "view 72 periods". I inspected the page, the table is nested inside various classes. Is there a simple way to extract the table?
Here it is:
var html = $(results);
var table = html.find(".view72PeriodsWrapper");
or as you changed your mind in the comment:
var table = html.find(".realtimeTableContainer");
See in action:
//$(function(){
function requestCrossDomain(site, callback) {
if (!site) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}
}
//$('#test').click(function(){
var url = 'https://www.emcsg.com/marketdata/priceinformation';
requestCrossDomain(url, 'someFunction');
function someFunction(results){
var html = $(results);
var table = html.find(".realtimeTableContainer");
$('#loadedContent').css("display","").html(table);
}
.realtimeTableHeaderContainer{display:none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script-->
<div id="result"></div>
<div id="loadedContent"></div>

unable to load javascript in webview until refreshed

i have an html file called room.html.erb which has some js code.when i click on a link it has to load the above page.but the page is loading correctly except js code.when i refresh it working fine.
code in room.html.erb
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script>
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
</script>
i couldn't able to figure it out why it is happening.
Wait until the DOM is loaded?
<script src="http://static.opentok.com/v2/js/opentok.min.js" type="text/javascript"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var apiKey = xxxxxx;//my apikey
var sessionId ="<%=#group.sessionId%>" ;
var token = "<%=#opentok_token%>";
var session;
OT.setLogLevel(OT.DEBUG);
session = OT.initSession(apiKey,sessionId);
session.on
({
streamCreated: function(event)
{
session.subscribe(event.stream,'subscribersDiv',{insertMode: 'append'});
}
});
session.connect(token,function(error){
if(error)
{
console.log(error.message);
}
else{
session.publish('myPublisherDiv',{width: 320,height: 240});
}
});
});
</script>
another method
add
<div id="myPublisherDiv"></div>
<div id="subscribersDiv"></div>

Google Contact API Error: Request via script load timed out. Possible causes: feed URL is incorrect; feed requires authentication

Hi I have an Error on Google Contact JavaScript API. The code was working fine from last day. But its not working today. Don't know what went wrong. :(
Request via script load timed out. Possible causes: feed URL is incorrect;
feed requires authentication.
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("gdata", "1.x");</script>
<script type="text/javascript">
google.setOnLoadCallback(initFunc);
var contactsService;
function setupContactsService() {
contactsService = new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
//logMeOut();
setupContactsService();
logMeIn();
getMyContacts();
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
// Set the maximum of the result set to be 5
query.setMaxResults(10000);
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var emailAddresses = contactEntry.getEmailAddresses();
for (var j = 0; j < emailAddresses.length; j++) {
var emailAddress = emailAddresses[j].getAddress();
}
}
}
function handleError(e) {
alert("There was an error!" + (e.cause ? e.cause.statusText : e.message));
//alert(e.cause ? e.cause.statusText : e.message);
}
function logMeOut() {
google.accounts.user.logout();
}
</script>
</head>
<body>
<IMG SRC="image.jpg"/> <!-- // Image for authentication -->
</body>
</html>
The following code works for me. Tested in Chrome, Safari, and FireFox. Summary of changes:
Check if logged in already, if so, don't attempt to log in again.
Removed google.setOnLoadCallback(initFunc); and replaced with a button click event. initFunc should never be called on page load.
IMPORTANT: If there is not an image on the page that is loaded from the same domain as your page, this will not work (per google).
Here's the code:
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
</script>
<script type="text/javascript">
var contactsService;
var scope = 'https://www.google.com/m8/feeds';
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');
}
function logMeIn()
{
var token = google.accounts.user.login(scope);
}
function initFunc()
{
setupContactsService();
if (google.accounts.user.checkLogin(scope))
{
getMyContacts();
}
else
{
logMeIn();
}
}
function getMyContacts()
{
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
// Set the maximum of the result set to be 5
query.setMaxResults(1);
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
var handleContactsFeed = function (result)
{
var entries = result.feed.entry;
for (var i = 0; i < entries.length; i++)
{
var contactEntry = entries[i];
var emailAddresses = contactEntry.getEmailAddresses();
for (var j = 0; j < emailAddresses.length; j++)
{
var emailAddress = emailAddresses[j].getAddress();
alert(emailAddress);
}
}
}
function handleError(e)
{
alert("There was an error!" + (e.cause ? e.cause.statusText : e.message));
}
function logMeOut()
{
google.accounts.user.logout();
}
</script>
</head>
<body>
<input type="button" onclick="initFunc();" value="Test" />
<img src="image.jpg" />
<!-- // Image for authentication -->
<script type="text/javascript">
if (google.accounts.user.checkLogin(scope))
{
setupContactsService();
getMyContacts();
}
</script>
</body>
EDIT
Added the following code right before the </body>
<script type="text/javascript">
if (google.accounts.user.checkLogin(scope))
{
setupContactsService();
getMyContacts();
}
</script>
#James Hill:
Yes, it's working when run from a server. There is a small bug though:-
When you run it for the first time, it doesn't return contacts. Try calling 'logMeOut()' just before you invoke 'initFunc()'. It will just go to the 'Grant Access' page and come back but not display any contacts. Please fix that :)

Categories