Firefox Addon SDK(jetpack): Passing page-script form data to index.js? - firefox

I want to pass the page script form data to index.js in my extension. What is the way to do it? I am trying to send it through content-script.js. To do this I am including my content-script.js file into the page-script. The content-script.js contains these lines of code-
function getInput(){
var url = document.getElementById('addr').value;
self.port.emit("addr",url);
}
Now from the page-script submit button I am calling getInput() function. But self.port.emit does not work here.

I have found out the solution. This can be done by creating DOM events.
In the page-script I have created a custom DOM event like this-
add.html->
<html>
<head>
<script>
function sendMessage() {
var url = document.getElementById('addr').value;
//console.log(url);
var event = document.createEvent('CustomEvent');
event.initCustomEvent("msg", true, true, url);
document.documentElement.dispatchEvent(event);
}
</script>
</head>
<body>
<form>
<input type="text" id="addr" name="addr">
<button onclick="sendMessage()">Add</button>
</form>
Next the helper.js listens for the new event and retrieves the message.
helper.js-
window.addEventListener("msg", function(event) {
var url = JSON.stringify(event.detail);
self.postMessage(url);
}, false);
Finally the index.js "panel" code looks like this-
var panels = require("sdk/panel");
var panel = panels.Panel({
width: 200,
height: 200,
contentURL: "./page.html",
contentScriptFile: "./helper.js",
onHide: handleHide,
onMessage: function(url) {
console.log(url); // displays the user input
}
});
Working fine. Is there other way to do this? Is this efficient one?
Also working fine with self.port.emit() and panel.port.on().

Related

Ajax busy indicator

How can I add a busy indicator before the Ajax popup appears on screen? I have been trying to follow several examples, but they are overly complex and very confusing for what seems should be an easy fix. Can anyone please help? Very new to Ajax. Thank you!
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert(response);
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="Start" value="Start" />
</body>
</html>
You have to add the indicator when starting the ajax call and remove it when the call returns.
But you should fix your html (input element is only valid inside a form tag) and then you have to prevent the form submission. If you follow this rules your code looks like this:
$(document).ready(function(){
$('.button').click(function(evt){
// preventing the form submission
evt.preventDefault();
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
// add indicator here (before the ajax request starts)
var $indicator = $('<div>Ajax in progress...</div>').appendTo('body');
$.post(ajaxurl, data, function (response) {
// removing the indicator inside the success handler of the ajax call.
$indicator.remove();
alert(response);
});
});
});

jQuery: Get next page via ajax and append it with animation

I am getting next page on my wordpress blog using jquery, finding the desired div and appending it to the existing one. This part works without a problem. But, what I need to do is, to add slideDown animation to it.
This is how my working code so far looks like:
$.get(next_page, function(data) {
var response = $(data);
var more_div = $(response).find('.FeaturedRow1').html();
$('.FeaturedRow1').append(more_div).slideDown('slow');
$('.navigation').not(':last').hide();
I tried adding hide() to response, more_div as well as append lines. In the first case, I get error stating that it cannot set property display of undefined.
In the second case, in the console it display HTML and says "has no method hide". I also tried adding a line $(more_div).hide() but again, I get the error "Uncaught TypeError: Cannot set property 'display' of undefined".
If I use hide in the 3rd line
$('.FeaturedRow1').hide().append(more_div).slideDown('slow');
it hides the whole FeaturedRow1 div and animates it, that takes me to the top of the div, which is what I don't want.
EDIT: Here's the important HTML structure and jQuery code for the desired section
<div class="FeaturedRow1">
<div class="postspage">
//list of posts here
</div>
<div class="navigation">
<span class="loadless">
//hyperlink to previous page
</span>
<span class="loadmore">
//hyperlink to next page
</span>
</div>
</div>
When you click on the hyperlink inside the loadmore, the following jQuery code gets called
$('.loadmore a').live('click', function(e) {
e.preventDefault();
var next_page = $(this).attr('href');
$.get(next_page, function(data) {
var $response = $(data);
var $more_div = $response.find('.FeaturedRow1').hide();
$more_div.appendTo('.FeaturedRow1').delay(100).slideDown('slow')
$('.navigation').not(':last').hide();
});
});
$('.loadless').live('click', function(e) {
e.preventDefault();
if ($('.postpage').length != 1) {
$('.postpage').last().remove();
}
$('.navigation').last().remove();
$('.navigation').last().show();
});
You get error as you are using html method which returns a string not a jQuery object, try the following.
var $response = $(data);
var $more_div = $response.find('.FeaturedRow1').hide();
$more_div.appendTo('.FeaturedRow1').delay(100).slideDown('slow');
//$('.navigation').not(':last').hide();
Update:
$.get(next_page, function(data) {
var $response = $(data);
var more_div = $response.find('.FeaturedRow1').html();
$('<div/>').hide()
.append(more_div)
.appendTo('.FeaturedRow1')
.delay(100)
.slideDown('slow')
$('.navigation').not(':last').hide();
});

Firefox extensions and full file paths from HTML form?

I have built a Firefox extension using the Addon SDK that opens up a new tab with a HTML page from the extensions directory and attaches a content script to it:
function openHtmlLoadFormTab(htmlFileName, jsWorkerFileName) {
tabs.open({
url: data.url(htmlFileName),
onReady: function(tab) {
var tabWorker = tab.attach({
contentScriptFile: [ data.url(jsJquery), data.url(jsWorkerFileName) ]
});
}
});
}
I have an <input type="file"> in the HTML file and some code that handles the "submit" event in the JS file (these files are given by htmlFileName and jsWorkerFileName respectively)
Because of security reasons, I cannot access the full file path in JS with document.getElementById('uploadid').value. I only get the file's name.
However, since this is a Firefox extension, I'm wondering if there is anyway to override this restriction?
I have been looking into netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead") and mozFullPath but I haven't been able to get it to work. I believe it's deprecated anyway?
The other solution is to build an XUL-based UI and prompt for the file there somehow, but I would like to know for sure if there is anyway to get this to work in HTML.
First edit with small example code
I built a small sample extension to illustrate how I'm doing things.
lib/main.js
var self = require('self');
var tabs = require('tabs');
var data = self.data;
var jsLoadForm = "load-form.js", htmlLoadForm = "load-form.html";
var jsJquery = 'jquery-1.8.0.min.js';
exports.onUnload = function(reason) {};
exports.main = function(options, callbacks) {
// TODO: remove this debugging line
openHtmlLoadFormTab(htmlLoadForm, jsLoadForm);
};
function openHtmlLoadFormTab(htmlFileName, jsWorkerFileName) {
tabs.open({
url: data.url(htmlFileName),
onReady: function(tab) {
var tabWorker = tab.attach({
contentScriptFile: [ data.url(jsJquery), data.url(jsWorkerFileName) ]
});
}
});
}
data/load-form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Form</title>
<script lang="text/javascript">
function fileChanged(e) {
// this is just the file name
alert("html js: files[0].name: " + e.files[0].name);
// mozFullPath is indeed empty, NOT undefined
alert("html js: files[0].mozFullPath: " + e.files[0].mozFullPath);
}
</script>
</head>
<body>
<form name="my-form" id="my-form" action="">
<div>
<label for="uploadid1" id="uploadlabel1">File (JS in HTML):</label>
<input type="file" name="uploadid1" id="uploadid1" onchange="fileChanged(this)"/>
</div>
<div>
<label for="uploadid2" id="uploadlabel2">File (JS in content script): </label>
<input type="file" name="uploadid2" id="uploadid2" onchange="fileChangedInContentScript(this)"/>
</div>
<div>
<label for="uploadid3" id="uploadlabel3">File (JS using jQuery in content script):</label>
<input type="file" name="uploadid3" id="uploadid3" />
</div>
</form>
</body>
</html>
data/load-form.js
$(document).ready(function() {
$("#uploadid3").change(function(e) {
// in jquery, e.files is null
if(e.files != null)
console.log("jquery: e.files is defined");
else
console.log("jquery: e.files is null");
// this works, prints the file name though
console.log("$('#uploadid3').val(): " + $("#uploadid3").val());
// this is undefined
console.log("$('#uploadid3').mozFullPath: " + $("#uploadid3").mozFullPath);
});
});
// this handler never gets called
function fileChangedInContentScript(e) {
alert("js content script: filechanged in content script called");
}
As you can see in main.js, I used jquery-1.8.0.min.js, downloaded from the jQuery website.
Note: I also tried these without jQuery included as a content script when I opened the tab in main.js, but no luck.
The conclusion is that mozFullPath is indeed empty when I access it from JS embedded in the HTML page and I cannot find a way to access mozFullPath from jQuery, nor can I find a way to add a onchange handler in load-form.html that's defined in load-form.js
Second edit with onchange handler in the load-form.js content-script
I added the following code to load-form.js to catch the onchange event.
I also removed the jQuery content script from main.js
document.addEventListener("DOMContentLoaded", function() {
try {
document.getElementById("uploadid2").addEventListener('change', function(e) {
console.log("addeventlistener worked!");
console.log("e: " + e);
console.log("e.target: " + e.target);
console.log("e.target.files: " + e.target.files);
console.log("e.target.files[0].name: " + e.target.files[0].name);
console.log("e.target.files[0].mozFullPath: " + e.target.files[0].mozFullPath);
});
console.log('added event listener')
} catch(e) {
console.log('adding event listener failed: ' + e);
}
}, false);
This still outputs an empty string for mozFullPath:
info: added event listener
info: addeventlistener worked!
info: e: [object Event]
info: e.target: [object HTMLInputElement]
info: e.target.files: [object FileList]
info: e.target.files[0].name: test.sh
info: e.target.files[0].mozFullPath:
Is there anyway to acquire the needed permissions? How can I get my hands on that full path? I need the full path so I can pass it to an application the extension launches. (There are workaround solutions where I can do without the full path, but they decrease the quality of the extension)
fileInput.value property is meant to be accessible to web pages so it will only give you the file name, not the full path - web pages have no reason to know the full path on your machine. However, as a privileged extension you should be able to access the File.mozFullPath property. In this particular case you would do it like this:
var files = document.getElementById('uploadid').files;
if (files.length > 0)
{
// Assuming that only one file can be selected
// we care only about the first entry
console.log(files[0].mozFullPath);
}
The big question of course is whether your code is allowed to access File.mozFullPath. I suspect that a content script in the Add-on SDK won't have the necessary privileges. The main extension code will have the privileges but getting to the input field from there is hard...

jquery .empty() issue: doesn't work in plugin

I have to write a simple plugin for ajax load.
Page code. (result by razor)
<a ajaxLoad="page" href="/Brand">Brand List</a>
<div id="plc1">
some content
</div>
<script type="text/javascript">
$(function () {
$("#plc1").ajaxPageLoad();
});
</script>
In js code.
jQuery.fn.ajaxPageLoad =
function () {
$('a[ajaxLoad*="page"]').click(function () {
$(this).empty();
$(this).load(this.href);
return false;
});
}
in page without this implementation empty() work properly but plug-in there is no effect.
what is wrong?
Thanks.
Seems that you're hoping this will refer to both the div and the a at the same time.
If I understand your code, you want to empty the element on which your plugin was called when the <a> element is clicked.
Currently, in the click() handler, this is the <a> element. You need to retain a reference to the <div> against which your plugin was called outside the handler.
jQuery.fn.ajaxPageLoad = function() {
// reference the <div> container (or whatever it ends up being)
var container = this;
$('a[ajaxLoad*="page"]').click(function() {
container.empty(); // empty the container
container.load( this.href ); // load into the container from the href
return false; // of the <a> that was clicked
});
};
$(function() {
$("#plc1").ajaxPageLoad();
});

Get current page URL from a firefox sidebar extension

I'm writing a sidebar extension for Firefox and need a way to get the URL of the current page so I can check it against a database and display the results. How can I do this?
I stumbled over this post while looking for an answer to the same question.
Actually I think it's as easy as
alert(window.content.location.href)
See also https://developer.mozilla.org/en/DOM/window.content
window.top.getBrowser().selectedBrowser.contentWindow.location.href;
might work, otherwise I think you need to use:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
This seems to work fine for me
function getCurrentURL(){
var currentWindow = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var currBrowser = currentWindow.getBrowser();
var currURL = currBrowser.currentURI.spec;
return currURL;
}
https://developer.mozilla.org/En/Working_with_windows_in_chrome_code
If you need to access the main browser from the code running in a sidebar, you'll something like what Wimmel posted, except the last line could be simplified to
mainWindow.content.location.href
(alternatively you could use 's API returning an nsIURI).
Depending on your task, it might make sense to run the code in the browser window instead (e.g. in a page load handler), then it can access the current page via the content shortcut and the sidebar via document.getElementById("sidebar").contentDocument or .contentWindow.
If you need only domain and subdomain;
Usage;
PageDomain.getDomain(); // stackoverflow.com
PageDomain.getSubDomain(); // abc.stackoverflow.com
Code;
PageDomain = {
getDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var domain = PageDomain.extractDomain(new String(docum.location));
return domain;
},
getSubDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var subDomain = PageDomain.extractSubDomain(new String(docum.location));
return subDomain;
},
extractDomain: function(host) {
var s;
// Credits to Chris Zarate
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
host=host.split('.');
if(host[2]!=null) {
s=host[host.length-2]+'.'+host[host.length-1];
domains='ab.ca|ac.ac|ac.at|ac.be|ac.cn|ac.il|ac.in|ac.jp|ac.kr|ac.nz|ac.th|ac.uk|ac.za|adm.br|adv.br|agro.pl|ah.cn|aid.pl|alt.za|am.br|arq.br|art.br|arts.ro|asn.au|asso.fr|asso.mc|atm.pl|auto.pl|bbs.tr|bc.ca|bio.br|biz.pl|bj.cn|br.com|cn.com|cng.br|cnt.br|co.ac|co.at|co.il|co.in|co.jp|co.kr|co.nz|co.th|co.uk|co.za|com.au|com.br|com.cn|com.ec|com.fr|com.hk|com.mm|com.mx|com.pl|com.ro|com.ru|com.sg|com.tr|com.tw|cq.cn|cri.nz|de.com|ecn.br|edu.au|edu.cn|edu.hk|edu.mm|edu.mx|edu.pl|edu.tr|edu.za|eng.br|ernet.in|esp.br|etc.br|eti.br|eu.com|eu.lv|fin.ec|firm.ro|fm.br|fot.br|fst.br|g12.br|gb.com|gb.net|gd.cn|gen.nz|gmina.pl|go.jp|go.kr|go.th|gob.mx|gov.br|gov.cn|gov.ec|gov.il|gov.in|gov.mm|gov.mx|gov.sg|gov.tr|gov.za|govt.nz|gs.cn|gsm.pl|gv.ac|gv.at|gx.cn|gz.cn|hb.cn|he.cn|hi.cn|hk.cn|hl.cn|hn.cn|hu.com|idv.tw|ind.br|inf.br|info.pl|info.ro|iwi.nz|jl.cn|jor.br|jpn.com|js.cn|k12.il|k12.tr|lel.br|ln.cn|ltd.uk|mail.pl|maori.nz|mb.ca|me.uk|med.br|med.ec|media.pl|mi.th|miasta.pl|mil.br|mil.ec|mil.nz|mil.pl|mil.tr|mil.za|mo.cn|muni.il|nb.ca|ne.jp|ne.kr|net.au|net.br|net.cn|net.ec|net.hk|net.il|net.in|net.mm|net.mx|net.nz|net.pl|net.ru|net.sg|net.th|net.tr|net.tw|net.za|nf.ca|ngo.za|nm.cn|nm.kr|no.com|nom.br|nom.pl|nom.ro|nom.za|ns.ca|nt.ca|nt.ro|ntr.br|nx.cn|odo.br|on.ca|or.ac|or.at|or.jp|or.kr|or.th|org.au|org.br|org.cn|org.ec|org.hk|org.il|org.mm|org.mx|org.nz|org.pl|org.ro|org.ru|org.sg|org.tr|org.tw|org.uk|org.za|pc.pl|pe.ca|plc.uk|ppg.br|presse.fr|priv.pl|pro.br|psc.br|psi.br|qc.ca|qc.com|qh.cn|re.kr|realestate.pl|rec.br|rec.ro|rel.pl|res.in|ru.com|sa.com|sc.cn|school.nz|school.za|se.com|se.net|sh.cn|shop.pl|sk.ca|sklep.pl|slg.br|sn.cn|sos.pl|store.ro|targi.pl|tj.cn|tm.fr|tm.mc|tm.pl|tm.ro|tm.za|tmp.br|tourism.pl|travel.pl|tur.br|turystyka.pl|tv.br|tw.cn|uk.co|uk.com|uk.net|us.com|uy.com|vet.br|web.za|web.com|www.ro|xj.cn|xz.cn|yk.ca|yn.cn|za.com';
domains=domains.split('|');
for(var i=0;i<domains.length;i++) {
if(s==domains[i]) {
s=host[host.length-3]+'.'+s;
break;
}
}
} else {
s=host.join('.');
}
// Thanks Chris
return s;
},
extractSubDomain:function(host){
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
return host;
}
}
From a Firefox extension popup ;
You'll need
"permissions": [
"activeTab"
]
in your manifest or possibly tabs instead of activeTab
async function getCurrentTabUrl(){
let tabs = await browser.tabs.query({active: true, currentWindow: true}) ;
return tabs[0].url ;
}
let hostUrl = await getCurrentTab();
alert(hostUrl);
This works from a firefox "popup" extension.
browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
.then(tabs => browser.tabs.get(tabs[0].id))
.then(tab => {
console.log(tab);
});
Hallo,
I have tried to implement this in JavaScript, because I need that in my project too, but all three possible solutions didn't work. I have also implemented a small site to test it, but this also didn't work.
Here is the source code of the small site:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Fall1 () {
alert(window.top.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall2() {
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
alert(mainWindow.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall3() {
alert(document.getElementById("sidebar").contentWindow.location.href);
}
</script>
</head>
<body>
<form name="Probe" action="">
<input type="button" value="Fall1"
onclick="Fall1()">
<input type="button" value="Fall2"
onclick="Fall2()">
<input type="button" value="Fall3"
onclick="Fall13()">
</form>
</body>
</html>

Resources