How to get the URL of clicked link? - firefox-addon

I am trying to create an add-on through Mozilla Add-On Builder. What I need to know is how to get the URL of a left clicked link in the active tab through the add-on and open it in a new tab.
I know this process involved adding an eventlistener through a page-mod and then using the tabs module, however I can't seem to get the syntax correct.
Edit: (This is what I have so far)
var Widget = require("widget").Widget;
var tabs = require('tabs');
var pageMod = require("page-mod");
exports.main = function() {
pageMod.PageMod({
include: '*',
contentScriptWhen: 'ready',
contentScript: "window.addEventListener('click', function(event) { self.port.emit( 'click',event.target.toString() )},false)",
onAttach: function(worker) {
worker.port.on("click", function(urlClicked) {
tabs.open(urlClicked);
});
}
});
};

The code you have there is mostly correct and works for me. There are two issues with your content script code however:
It needs to call event.preventDefault() to prevent the browser from following the link. Otherwise the linked page will be loaded both in the current tab and the new tab opened by your extension.
It doesn't check whether event.target is actually a link. It could be a child node of the link or it might not be a link at all.
Altogether, your content script should look like this:
window.addEventListener("click", function(event)
{
var link = event.target;
while (link && link.localName != "a")
link = link.parentNode;
if (link)
{
self.port.emit("click", link.href);
event.preventDefault();
}
}, false);
For a non-trivial content script like this, you shouldn't use contentScript parameter but rather put it into its own file in the data/ directory. You can then use contentScriptFile parameter when constructing the panel:
contentScriptFile: require("self").data.url("contentScript.js"),

Related

Open a link from a webview in a chrome app within the same webview

I am trying to create a chrome kiosk app that will open a webpage that contains links in a webview and then load the links within the same webview. However, the links on the webpage that I am working with are target="_blank" and I am getting the error <webview>: A new window was blocked wehn they are clicked. I found a solution to this here and tried to implement its suggestion like this:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create(
'window.html',
{ 'width': 1000, 'height': 1000 },
function(win) {
win.contentWindow.onload = function() {
var webview = win.contentWindow.document.querySelector('#webview');
webview.addEventListener('newwindow', function(e) {
chrome.app.window.create(e.targetUrl,window.open()
});
};
}
);
});
However, I would like to have the link open not in the browser, but in the same webview that the link was launched from.
Is there some way to capture the target URL, strip it of its target="_blank" attribute, and then load the URL in the original webview?
An event listener in the content script will capture the URL when the newwindow event is fired. Once the URL is captured, it's a simple thing to set the URL as the webview's source.
var webview = document.querySelector('#webview');
webview.addEventListener('newwindow', function (e) {
//prevent the link from attempting to open a new window
e.preventDefault();
webview.src = e.targetUrl;
});
Because this script doesn't open any new windows, it doesn't have to be run specifically in the app's background script.

Firefox addon opens tab with content, copy/paste of the tabs url will not load page fully

I have an addon that places an ActionButton on the toolbar. When the ActionButton is clicked the code below is run.
The code opens a new tab and provides some html and js, this acts as the addon's UI.
The url of the new tab is:
resource://jid1-qljswfs6someid-at-jetpack/addon-firefox/data/html/view.html
If I copy/paste that url into another new tab manually, the html displays but the js logic is not loaded. Is there a way to do this without clicking the ActionButton? So I could maybe bookmark the addon instead of having the ActionButton take up space.
Code:
Tabs.open({
url: require("sdk/self").data.url('html/view.html'),
onReady: function onReady(tab) {
worker = tab.attach({
contentScriptFile: [
require("sdk/self").data.url.get('lib/lib1.js'),
require("sdk/self").data.url.get('js/lib1.js')
],
onMessage: function(message) {
console.log('stuff done');
}
});
}
});
In order to run it whenever the site from data.url('html/view.html') is loaded you would have to use page-mod instead of manually attaching to the document to the tab.
Your include pattern would be something like data.url('html/view.html') + "*", so it also attaches to the page if there is a hash or a query to the document.

PhoneGap InAppBrowser: open iOS Safari Browser

In our PhoneGap iOS application, we are using the InAppBrowser plugin to display some content, and we need to open a page in Safari from within the InAppBrowser.
How can we have links from within the InAppBrowser open in Safari?
From the phonegap documentation:
Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
var ref = window.open(url, target, options);
ref: Reference to the InAppBrowser window. (InAppBrowser)
url: The URL to load (String). Call encodeURI() on this if the URL contains Unicode characters.
target: The target in which to load the URL, an optional parameter that defaults to _self. (String)
_self: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the InAppBrowser.
_blank: Opens in the InAppBrowser.
_system: Opens in the system's web browser.
So to answer your question, use:
window.open(your_url, '_system', opts);
Note that the domain will need to be white-listed.
Update 4/25/2014:
I think I kind of misunderstood the question (thanks to commenter #peteorpeter) -- you want to have some way to click a link in the InAppBrowser and have that open in the system browser (e.g. Mobile Safari on iOS). This is possible, but it will require some forethought and cooperation between the app developer and the person responsible for the links on the page.
When you create an IAB instance, you get a reference to it back:
var ref = window.open('http://foo.com', '_blank', {...});
You can register a few event listeners on that reference:
ref.addEventListener('loadStart', function(event){ ... });
This particular event is fired every time the URL of the IAB changes (e.g. a link is clicked, the server returns a 302, etc...), and you can inspect the new URL.
To break out into the system browser, you need some sort of flag defined in the URL. You could do any number of things, but for this example let's assume there's a systemBrowser flag in the url:
.....html?foo=1&systemBrowser=true
You'll look for that flag in your event handler, and when found, kick out to the system browser:
ref.addEventListener('loadStart', function(event){
if (event.url.indexOf('systemBrowser') > 0){
window.open(event.url, '_system', null);
}
});
Note that this is not the best method for detecting the flag in the url (could lead to false positives, possibly) and I'm pretty sure that PhoneGap whitelist rules will still apply.
Unfortunately target=_system does not work from within the InAppBrowser. (This would work if the link originated in the parent app, though.)
You could add an event listener to the IAB and sniff for a particular url pattern, as you mention in your comments, if that fit your use case.
iab.addEventListener('loadstart', function(event) {
if (event.url.indexOf("openinSafari") != -1) {
window.open(event.url, '_system');
}
}
The 'event' here is not a real browser event - it is a construct of the IAB plugin - and doesn't support event.preventDefault(), so the IAB will also load the url (in addition to Safari). You might try to handle that event within the IAB, with something like:
iab.addEventListener('loadstop', function(event) {
iab.executeScript('functionThatPreventsOpenInSafariLinksFromGoingAnywhere');
}
...which I have not tested.
This message is for clarification:
If you open an another with window.open by catching a link on loadstart, it will kill yor eventhandlers that assigned to first IAB.
For example,
iab = window.open('http://example.com', '_blank', 'location=no,hardwareback=yes,toolbar=no');
iab.addEventListener('loadstop', function(event) {console.log('stop: ' + event.url);});
iab.addEventListener('loaderror', function(event) { console.log('loaderror: ' + event.message); });
iab.addEventListener('loadstart', function(event) {
if (event.url.indexOf("twitter") != -1){
var ref2 = window.open(event.url, '_system', null);
}
});
When the second window.open executed, it will kill all the event listeners that you binded before. Also loadstop event will not be fired after that window.open executed.
I'm finding another way to avoid but nothing found yet..
window.open() doesn't work for me from within an InAppBrowser, whether or not I add a script reference to cordova.js to get support for window.open(...'_system'), so I came up with the following solution which tunnels the "external" URL back to the IAB host through the hashtag so it can be opened there.
Inside the InAppBrowser instance (I'm using AngularJS, but you can replace angular.element with jQuery or $ if you're using jQuery):
angular.element(document).find('a').on('click', function(e) {
var targetUrl = angular.element(this).attr('href');
if(targetUrl.indexOf('http') === 0) {
e.preventDefault();
window.open('#' + targetUrl);
}
});
Note that that's the native window.open above, not cordova.js's window.open. Also, the handler code assumes that all URLs that start with http should be externally loaded. You can change the filter as you like to allow some URLs to be loaded in the IAB and others in Safari.
Then, in the code from the parent that created the InAppBrowser:
inAppBrowser.addEventListener('loadstart', function(e) {
if(e.url.indexOf('#') > 0) {
var tunneledUrl = e.url.substring(e.url.indexOf('#') + 1);
window.open(tunneledUrl, '_system', null);
}
});
With this solution the IAB remains on the original page and doesn't trigger a back-navigation arrow to appear, and the loadstart handler is able to open the requested URL in Safari.

Can't recieve port message from main.js in content script

I am trying to send a message via port from my main.js to my content script for my panel. I've tried many things without luck, however sending a message from the content script to main.js works perfectly.
Here is what my main.js looks like:
var data = require("self").data;
var setting = require("panel").Panel({
width: 250,
height: 130,
contentURL: data.url("www.google.com"),
contentScriptFile: data.url("script.js")
});
require("widget").Widget({
id: "sorter1",
label: "Search Result Sorting",
contentURL: data.url("icon.ico"),
panel: setting
});
setting.port.emit("message");
And here is my content script:
self.on("message", function(addonMessage) {
document.innerHTML = "Got Message"
});
I had this figured out a few days ago, just haven't had the time to post here.
A few things to keep in mind when using panels:
Pannel page is loaded when extension is loaded, not when it is shown.
Content script of the panel page is injected into the panel page when the page is shown.(when contentScriptWhen property is default)
Content scripts dont have access to add-on SDK resources.
This is how I implemented it
In main.js
panel.on("show", function() {
panel.port.emit("message");
});
In panel content script
self.port.on("message", function() {
//doThings
});
port.emit() doesn't need a second argument, though second argument is what will be passed to the content script for
function(secondArg) {
}
[Update] Sorry, I didn't fully read the code.
First off, you actually need to send the panel a message, eg
setting.port.emit('message', someData);
For the second part: I think you want:
self.port.on("message", function(addonMessage) {
document.innerHTML = "Got Message"
});
The relevant docs are here:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/content-scripts/using-port.html

Getting page title in Firefox add-on using Add-on SDK

I am trying to get page title on every page using new Firefox add-on builder. How can I do that?
Edit
More info
I want to get page title on every page load event .
It is actually the very first example for the tabs package:
var tabs = require("tabs");
for each (var tab in tabs)
console.log(tab.title);
See tab.title.
Edit: If you need to know the title of each page as it loads rather than capture the current state then you should use the page-mod package:
var pageMod = require("page-mod");
pageMod.PageMod({
include: "*",
contentScriptWhen: "end",
contentScript: 'console.log(document.title);'
});
The documentation has some info on how a content script can communicate with the add-on, e.g. to send it this page title.
If you are only interested in top-level documents then you can still use the tabs package:
var tabs = require("tabs");
tabs.on("ready", function(tab) {
console.log(tab.title);
});
"ready" events won't get fired if the page is served from back-forward cache.
'pageshow' event is the appropriate event to listen to.
var tabs = require("sdk/tabs");
function onOpen(tab) {
tab.on('pageshow', function(tab) {
console.log('title: '+ tab.title);
}
tabs.on('open', onOpen);

Resources