"chrome.tabs.query" can't Execution my code - javascript

function onWindowLoad() {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
tabUrl = tabs[0].url;
alert(tabUrl);//taburl is Successfully displayed in my browser
$("#txtUrl").val(tabUrl);//This line of code is not implemented
alert("hello");//cant't alert hello
});
window.onload = onWindowLoad;
please help me :I want to get the url to my page, but after running the code and nothing happens,How to deal with it?

Related

CasperJS or PhantomJS - how to export variable in-between functions?

With CasperJS or PhantomJS I want to:
1.) Visit 1 page and get Captcha image.
2.) Then decode Captcha on local server.
3.) Then submit the decoded Captcha results to 1. page.
4.) And get result (HTML).
A simple test assuming the Captcha code is 12345 to test that all values are entered and executed correctly like:
var casper = require('casper').create({ verbose: true, logLevel: "debug" });
var NUMBER_TO_CHECK = '356702087654321';
var DECODED_CAPTCHA = '12345';
casper.start('https://checkcoverage.apple.com/', function () {
this.sendKeys('input#serial-number', NUMBER_TO_CHECK);
this.sendKeys('input#captcha-input', DECODED_CAPTCHA);
this.mouseEvent('click', '.button-label', '50%', '50%');
this.wait(1000, function () {
this.echo('WAIT DONE');
});
});
casper.then(function (e) {
this.capture('logged-in.png');//print screen shot after click
});
casper.run();
This code snippet above gives Success result and says the given Captcha 12345 is incorrect which is true.
Now I need to modify this snippet so I can get the Captcha Image and process it on local server, and I have tried like:
var casper = require('casper').create({ verbose: true, logLevel: "debug" });
var NUMBER_TO_CHECK = '356702087654321';
casper.start('https://checkcoverage.apple.com/', function () {
this.sendKeys('input#serial-number', NUMBER_TO_CHECK);
// Get Encoded Captcha as Var
var captcha_encoded = casper.evaluate(function() {
return document.getElementsByClassName('captcha-image')[0].outerHTML;
});
// Post Encoded Captcha for decoding processing.
casper.then(function() { this.open('http://127.0.0.1/decode_captcha.php', {
method: 'post', data: { 'data': captcha_encoded } });
});
// Return Decoded Captch
casper.then(function() { var DECODED_CAPTCHA = this.getHTML('body');
this.echo(DECODED_CAPTCHA);
return(DECODED_CAPTCHA);
});
// How to Submit the Decoded Captcha result here ?
// Stuck here....
// ...
// this.sendKeys('input#captcha-input', DECODED_CAPTCHA);
// this.mouseEvent('click', '.button-label', '50%', '50%');
this.wait(1000, function () {
this.echo('WAIT DONE');
});
});
casper.then(function (e) {
this.capture('logged-in.png');//print screen shot after click
});
casper.run();
With this.echo(DECODED_CAPTCHA); I get the Decoded Captcha result in Console logs. But logged-in.png shows Screenshot from Local server, not from 1. page.
Question: How can I submit the var DECODED_CAPTCHA result to 1. page?
This is kind a delicate question. As per official documentation there is no support for parallel browsing
Is it possible to achieve parallel browsing using CasperJS?
And for your use case you need exactly that to keep your Captcha the same.
You can try examples posted in this group to see if it helps you.

Asynchronous Message Sending In Google Chrome Extension Popup

I have been researching asynchronous function calls and how to set variables to values from them and have had a lot of trouble with it. I want to create a port to message with my file content.js on the extension.
To do this I need to receive the tab of the window that I have open, and use its attribute id in the chrome.tabs.connect() function.
This implementation fails to reach any console.log() calls but I don't understand asynchronous programming well enough to understand. Can anyone help with this? My problem is that the two files aren't communicating, so the port isn't opening.
<script language = "Javascript">
function foo(callback){
var port = chrome.tabs.connect(chrome.tabs.query({ currentWindow: true, active: true }, function(tabs) {
//sets curTab to current tab
console.log(tabs[0]);
var curTab;
setTimeout(function(tabs) {
curTab = tabs[0];
console.log(curTab);
}, 5000);
}),{name: "mode"})
//both files are preset to this so no need to message
var mode = "on";
document.getElementById("stop").onclick = function(){
if(mode === "off")
mode = "on";
else
mode = "off";
setMode();
console.log("clikityclik");
};
console.log(mode);
function setMode(){
/*sends message to port*/
if(port)
port.postMessage({newMode: mode});
else{
console.log("error: port not created");
}
}
}
the relevant code from my content.js file is below. I call this function once
function getMode(){
/*receives message from port
**communicates with sandboxed.html
*/
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "mode");
port.onMessage.addListener(function(msg) {
if (msg.newMode){
mode = msg.newMode;
console.log("Mesage received: "+mode);
}
else
console.log("error receiving new mode, last mode was: " + mode);
});
});
}
The goal of this program is for the first script to send messages to the content.js when a div is clicked and for the 'content.js' file to receive those messages whenever they are sent.
the solution was to make a function that creates the port, with an input of tab. Basically, getTab will try to get the the value of the tab, and if we do have a tab it will run the callback function which is createPort which contains the information necessary to create the port and also the event handler for the click on the div.
function getTab(callback){
chrome.tabs.query({ currentWindow: true, active: true }, function(tabs) {
console.log(tabs[0]);
callback(tabs[0]);
});
}
function createPort(tab){
var port = chrome.tabs.connect(tab.id,{name: "mode"});
document.getElementById("stop").onclick = function(){
if(mode === "off")
mode = "on";
else
mode = "off";
setMode(port);
console.log("clikityclik");
};
}
var mode = "on"; //mode is preset to on in content.js
getTab(createPort);

how to get background.js to change based on options.js

I am currently making a Google Chrome extension, and in the options I want the user to be able to choose between it being always on or only activating when clicked. To do this, I need an options.js and a background.js file, which I have. However, I am having a lot of trouble getting them to communicate properly. I tried using the chrome.storage api, but it won't do anything.
Here is my code for background.js:
chrome.browserAction.onClicked.addListener(function() {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {"message": tabs[0].url}, function(response));
});
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
// console.log(tabs.length);
chrome.tabs.sendMessage(tabs[0].id, {"message": tabs[0].url}, function(response) {});
});
}
});
And here is my code for options.js:
// Saves options to chrome.storage
function save_options() {
var behavior = document.getElementById('behavior').value;
chrome.storage.sync.set({
extensionBehavior: behavior
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved!';
setTimeout(function() {
status.textContent = '';
}, 1000);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
// Use default value color = 'red' and likesColor = true.
chrome.storage.sync.get({
extensionBehavior: 'onClick'
}, function(items) {
document.getElementById('behavior').value = items.extensionBehavior;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
save_options);
If the behavior is set to "onClick", I only want the chrome.browserAction.onClicked.addListener portion to be executed. If the behavior is set to 'alwaysOn', then I only want the chrome.tabs.onUpdated.addListener portion to be executed. As far as debugging goes, both of those chunks work the way they're supposed to. I just need to know how to get one or the other to run based on the current options.
For the communication between option and background, it would be quite easy when you choose the localStorage to pass info between them. http://www.w3schools.com/html/html5_webstorage.asp

Chrome extension: Display a popup window once PDF Viewer (pdf.js) processes a PDF

I am new to pdf.js and google chrome extensions. I am using pdf.js to view PDF files in Chrome (https://github.com/mozilla/pdf.js/tree/master/extensions/chromium).
WHAT I WANT TO IMPLEMENT: Once my PDF is loaded and processed by PDF viewer (pdf.js), I want to check if a user is logged into my website via XmlHttpRequest. Then I want to create a popup window showing the user's name or ask him/her to login.
I've added checkLogin(); function to the following script (https://github.com/Rob--W/chrome-api/tree/master/chrome.tabs.executeScriptInFrame).
checkLogin(); opens a new popup window (dialog.html)
chrome.tabs.executeScriptInFrame.js :
function checkLogin() {
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function(tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true,
height: 200, width:500
});
});
}
dialog.html displays the message returned from dialog.js (containing username or asking user to login)
dialog.html :
<html>
<head><title>Dialog test</title></head>
<body>
<div id="output"></div>
<script src="dialog.js"></script>
</body>
</html>
dialog.js :
connect();
function connect() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "sendingcookies.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status ==200 ) {
var response = xhr.responseText;
document.getElementById('output').innerHTML = response;
}
}
xhr.send(null);
}
THE PROBLEM: If I insert checkLogin(); function in background.js, the script runs when the extension is loaded. However, I want to run this function each time a PDF is loaded and processed by pdf.js. I am not sure how to proceed as I'm still familiarizing with pdf.js code.
Any tips on how to implement this correctly will be awesome. Thanks in advance for your help!
So I figured out how to implement this. I'm posting this answer for those that may be interested.
As suggested by user #Luc on the thread How to know if PDF.JS has finished rendering? , I added my checkLogin(); function to this existing function in viewer.js.
document.addEventListener('textlayerrendered', function (e) {
var pageIndex = e.detail.pageNumber - 1;
var pageView = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
//Added this code - creates popup window once PDF has finished rendering
if (event.detail.pageNumber === PDFViewerApplication.page) {
checkLogin();
function checkLogin() {
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function(tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true,
// incognito, top, left, ...
height: 300, width:500
});
});
}
}
}, true);
As a result, my popup window loads while/once the PDF has finished rendering. It's pretty neat!

Closing Tab in Chrome Extension

I have a function called in popup.html that creates a tab, inserts a mailto to trigger a local (or gmail) mail event. It's my desire for it to then close itself. I've tried numerous things, but it seems like I need something that does the equivalent of:
tabId = chrome.tabs.query(I DON'T KNOW!);
chrome.tabs.remove(tabId);
here's the current code:
var query = { active: true, currentWindow: true };
function callback(tabs) {
var currentTab = tabs[0];
console.log(currentTab);
}
chrome.tabs.remove(chrome.tabs.query(query, callback));
but it's not working.
if useful, here's how I create the tab (which does work as desired):
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
getTabs(tabs, function(full_mail_link){
chrome.tabs.create({ url: full_mail_link });
});
});
any help would be greatly appreciated!
I don't know what your getTabs function does. Yet if you know how to find the tab id of the tab you want all you need to do is
chrome.tabs.remove(tabId, optionalCallback);
this must be work:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.remove(tab.id);
});
This should work:
//create the tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
getTabs(tabs, function(full_mail_link){
chrome.tabs.create({ url: full_mail_link }, callBackOnCreate);
});
});
function callBackOnCreate(tab)
{
globalCreatedTab = tab.id;
}
chrome.tabs.query({'active': true}, function(tabs) {
for (var i = 0; i < tabs.length; ++i)
{
if (tabs[i].id === globalCreatedTab)
{
chrome.tabs.remove(tabs[i].id, [optional callback]);
}
}
});
Solution: use the query function with the callback and execute the remove function in the callback.
It looks like normal window.open and window.close() should also work,
The tab-id is an integer or an array containing integers.

Categories

Resources