So I've collected 5 different methods to do this, none of which work from within a panel. Firefox is stunningly effective at blocking access to a basic task.
Here's what I've tried:
Attempt 1:
var url = window.top.getBrowser().selectedBrowser.contentWindow.location.href;
Error: window.top.getBrowser is not a function
Attempt 2:
var url = window.content.document.location;
Error: Permission denied to access property 'document'
Attempt 3:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
var url = mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
Error: Permission denied to create wrapper for object of class UnnamedClass
Attempt 4:
var url = window.content.location.href;
Error: Permission denied to access property 'href'
Attempt 5:
var currentWindow = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var currBrowser = currentWindow.getBrowser();
var url = currBrowser.currentURI.spec;
Error: Permission denied to get property XPCComponents.classes
Coding this for Chrome was a breeze. Not sure why this is so tough for FF.
Anyone got a solution?
I think you can use firefox local object:
var url = gBrowser.contentDocument.location;
I guess "Firefox Addon panel" refers to the Addon SDK's panel module?
If so you're probably trying to use those snippets in a content script. Instead you have to send an event to the main addon's code (example), and in the main addon's code use the tabs module:
require("tabs").activeTab.url
[update] complete testcase, which works for me:
// http://stackoverflow.com/questions/7856282/get-current-url-from-within-a-firefox-addon-panel
exports.main = function() {
var panel = require("panel").Panel({
contentURL: "data:text/html,<input type=button value='click me' id='b'>",
contentScript: "document.getElementById('b').onclick = " +
"function() {" +
" self.port.emit('myEvent');" +
"}"
});
panel.port.on("myEvent", function() {
console.log(require("tabs").activeTab.url)
})
require("widget").Widget({
id: "my-panel",
contentURL: "http://www.google.com/favicon.ico",
label: "Test Widget",
panel: panel
});
};
Related
I am trying to create a Firefox extension to block search terms on school computers. I'd like to prohibit a list of keywords, but the blocking doesn't seem to be working.
I found an example through a plugin gallery here:
https://github.com/mdn/webextensions-examples/blob/master/proxy-blocker/background/proxy-handler.js
This plugin listens to blocked hosts, and then basically returns localhost. I'd like to do the same, but when search terms are added in. I used the code in the example above as a starting point.
Here is the code I have so far:
// Initialize the list of blocked hosts
let blockedHosts = ["www.duckduckgo.com", "www.google.com"];
let blockedTerms = ["games", "minecraft", "legos"];
// Set the default list on installation.
browser.runtime.onInstalled.addListener(details => {
browser.storage.local.set({
blockedHosts: blockedHosts
});
});
// Get the stored list
browser.storage.local.get(data => {
if (data.blockedHosts) {
blockedHosts = data.blockedHosts;
}
});
// Listen for changes in the blocked list
browser.storage.onChanged.addListener(changeData => {
blockedHosts = changeData.blockedHosts.newValue;
});
// Managed the proxy
// Listen for a request to open a webpage
browser.proxy.onRequest.addListener(handleProxyRequest, {urls: ["<all_urls>"]});
function handleProxyRequest(requestInfo) {
let urlToCheck = new URL(requestInfo.documentUrl)
let searchString = urlToCheck.search;
const url = new URL(requestInfo.url);
let found;
blockedTerms.map((term) =>{
if(searchString.search(term) != -1){
found = true
}
})
if ( blockedHosts.indexOf(url.hostname) != -1 & found) {
return {type: "https", host: "127.0.0.1", port: 65535};
}
// Return instructions to open the requested webpage
return {type: "direct"};
}
// Log any errors from the proxy script
browser.proxy.onError.addListener(error => {
console.error(`Proxy error: ${error.message}`);
});
The URL that the browser creates is https://duckduckgo.com/?t=ffab&q=games&ia=web for example. I can determine that the term "games" was found, and that it was found in a duck duck go search, but the proxy wont work and the browser wont stop the user from going to the page.
Any help would be appreciated!
To start with, in a school environment, I suppose they have to use school net connection. It would be a lot easier to block at the main internet connection instead of creating and installing an addon on each computer (that might be altered or bypassed with another browser).
However, to answer your question, the following would be one (simpler) way of doing that using webRequest.onBeforeRequest:
// add a listener for web requests
browser.webRequest.onBeforeRequest.addListener(process, {
urls: ['*://*/*']
},
['blocking']
);
function process(e) {
// e.url is the target url
// no need for storage as the filter-list is hard-coded
const blockedHosts = ['www.duckduckgo.com', 'www.google.com'];
const blockedTerms = ['games', 'minecraft', 'legos'];
const hostRegExp = new RegExp(`^https?://(${blockedHosts.join('|')})/`, 'i');
const termRegExp = new RegExp(`(${blockedTerms.join('|')})`, 'i');
// if matches above criteria, redirect to 127.0.0.1
if (hostRegExp.test(e.url) && termRegExp.test(e.url)) {
return {redirectUrl: 'https://127.0.0.1:65535/'};
}
}
I'm trying to upload an image via nativescript-background-http plugin.
this my code:
var session = bghttp.session("image-upload");
var request = {
url: 'http://localhost:4200/',
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": imageFile.name
},
description: "{ 'uploading': " + imageFile.name + " }"
};
var task = this.session.uploadFile(path, request);
when I try to build my app, it will show the error:
TypeError: Cannot set property 'NAMESPACE' of undefined
The line of error is exactly this line:
var task = this.session.uploadFile(path, request);
any idea?
I've got a solution for you. To upload image using nativescript background http is now easy using a file stream method on your backend server.
https://www.ekpotoliberty.com/read/NativeScript-Image-Uploading-to-NodeJs-Api-+-Cloudinary-using-NativeScript-Background-HTTP/5dad52c76dc813685f8da26f
Follow the link above this will help you get through for nativescript core.
We have the following script that works fine on all browsers.
However when the same script is placed inside the Fullcalender eventRecieve function (external events drag, drop and re render) the script does not post data to insert_events.php - but this only happens in Firefox- it does post data as expected in both Chrome and Edge. So in summary we have a situation as follows:
Edge, Chrome, FF - script is standalone --> posts data as expected
Edge and Chrome - script is inside eventRecieve --> posts data as
expected
FF script is inside eventRecieve -->fails to post data as expected
Code:
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
var propertyid = "WR388GG-8621";
$.post("insert_events.php?propertyid=" + propertyid, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
);
We originally thought this issue was down to the Ajax code with FF and
searched high and low for some ideas and spent a day trying to work out what was going on. But actually the problem is only showing up in Firefox and only when the script is triggered by Fullcalendar's eventRecieve function as below.
Code:
eventReceive: function(event) {
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
$.post("insert_events.php?propertyid=" + id, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
$('#calendar').fullCalendar('rerenderEvents');
window.location = 'new place to go';
},
Any ideas?
Credit goes to A Dyson on this one. It would seem that Firefox alone will trigger the redirect (window.location = 'new place to go';) before the Ajax call is made. The same is not true of Chrome or Edge - which handle the Ajax call first. Please upvote A Dyson's comment which should be the accepted answer. Apologies for dismissing A Dysons correct comment to soon.
How show something from parse.com data base ? Give me code please. I just only sturted learning js. For example how show all users. Or how show information about one user. Help please )
Hi I would suggest you to start learning parse ans JS with all the proper documentation provided. Documentations
If you are looking for a simple example using Parse and JS, take a look at the below code,
myObject.fetch({
success: function(myObject) {
// The object was refreshed successfully.
},
error: function(myObject, error) {
// The object was not refreshed successfully.
// error is a Parse.Error with an error code and message.
}
});
Or you can refer to the below example also, where we can make use of handlebar.js to display each blog object.
$(function() {
Parse.$ = jQuery;
// Replace this line with the one on your Quickstart Guide Page
Parse.initialize("KEYS", "KEYS");
// Your Parse application key
var Blog = Parse.Object.extend("Blog");
var Blogs = Parse.Collection.extend({
model: Blog
});
var blogs = new Blogs();
blogs.fetch({
success: function(blogs){
console.log(blogs);
var blogsView = new BlogsView({ collection: blogs });
blogsView.render();
$('.main-container').html(blogsView.el);
},
error: function(blog, error){
console.log(error);_
}
});
var BlogsView = Parse.View.extend({
template: Handlebars.compile($('#blogs-tpl').html()),
render: function(){
var collection = { blog: this.collection.toJSON() };
this.$el.html(this.template(collection));
}
});
});
I want to sniff the packets with my addon. I am using this Stack overflow question as hint. My full code is this:
// This is an active module of the Add on
exports.main = function() {
var {Cc, Ci,Cu} = require("chrome");
var widgets = require("widget");
var windows = require("windows").browserWindows;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "activityDistributor",
"#mozilla.org/network/http-activity-distributor;1",
"nsIHttpActivityDistributor");
let httpTrafficObserver = {
/**
* Begin observing HTTP traffic that we care about,
* namely traffic that originates inside any context that a Heads Up Display
* is active for.
*/
startHTTPObservation: function httpObserverFactory()
{
// creates an observer for http traffic
var self = this;
var httpObserver = {
observeActivity :
function observeActivity(aChannel,
aActivityType,
aActivitySubtype,
aTimestamp,
aExtraSizeData,
aExtraStringData)
{
if (aActivityType ==
activityDistributor.ACTIVITY_TYPE_HTTP_TRANSACTION ||
aActivityType ==
activityDistributor.ACTIVITY_TYPE_SOCKET_TRANSPORT) {
aChannel = aChannel.QueryInterface(Ci.nsIHttpChannel);
let transCodes = this.httpTransactionCodes;
if (aActivitySubtype ==
activityDistributor.ACTIVITY_SUBTYPE_REQUEST_HEADER ) {
let httpActivity = {
url: aChannel.URI.spec,
method: aChannel.requestMethod,
channel: aChannel
};
}
}
},
httpTransactionCodes: {
0x5001: "REQUEST_HEADER",
0x5002: "REQUEST_BODY_SENT",
0x5003: "RESPONSE_START",
0x5004: "RESPONSE_HEADER",
0x5005: "RESPONSE_COMPLETE",
0x5006: "TRANSACTION_CLOSE",
0x804b0003: "STATUS_RESOLVING",
0x804b0007: "STATUS_CONNECTING_TO",
0x804b0004: "STATUS_CONNECTED_TO",
0x804b0005: "STATUS_SENDING_TO",
0x804b000a: "STATUS_WAITING_FOR",
0x804b0006: "STATUS_RECEIVING_FROM"
}
};
this.httpObserver = httpObserver;
activityDistributor.addObserver(httpObserver);
}
};
var example = windows.open("http://www.example.com");
var widget = widgets.Widget({
id: "close-window",
label: "Close window",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function() {
example.close();
}
});
};
The browser console tells me Reference Error: XPCOMUtils is not defined. Why's that?
UPDATE: I applied Wladimir Palant's fix but now there's another error:
An exception occurred.
Traceback (most recent call last):
File ".../XPCOMUtils.jsm", line 231, in XPCU_defineLazyServiceGetter
File ".../XPCOMUtils.jsm", line 208, in XPCU_defineLazyGetter
TypeError: aObject.__defineGetter__(aName, function()
{delete aObject[name];return aObject[name] == aLambda.apply(aObject);})
is not extensible
When you use Cu.import() in an Add-on SDK extension the variables aren't being added automatically (bug 683217). The work-around is simple:
var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Concerning your update, I'm not sure what this is that you try to define a getter on but it is definitely not the global object - and Object.freeze() has been applied to it so that no new properties can be added (that's what is causing "not extensible" error). Instead it would make sense to define your lazy getter on the httpTrafficObserver object:
XPCOMUtils.defineLazyServiceGetter(httpTrafficObserver, "activityDistributor",
"#mozilla.org/network/http-activity-distributor;1",
"nsIHttpActivityDistributor");
Of course, in startHTTPObservation you would use self.activityDistributor instead of assuming that activityDistributor is a global variable.
this comes up on bing top search when searching how to lazy load.
but i didnt learn how to use till i read this article. so for all those users coming across this topic read this it makes it very easy to understand. i now lazy load succesfully.
http://mike.kaply.com/2011/02/08/adding-services-to-your-firefox-add-on/