I have a weird bug in my addon,
the addon itself needs to add a request header parameters for a specific domain,
it's all working, but the bug is, that the observer http-on-modify-request is not called at start, only if I reload the page, then it's working.
I mean:
I go to mysite.com/ - no header modified,
I reload page - header modefied
reload again - header modefied
new tab at mysite.com/ - no header modified
reload tab - header modefied
My code, I'm using the addon sdk:
exports.main = function(options,callbacks) {
// Create observer
httpRequestObserver =
{
observe: function(subject, topic, data)
{
if (topic == "http-on-modify-request") {
//only identify to specific preference domain
var windowsService = Cc['#mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
var uri = windowsService.getMostRecentWindow('navigator:browser').getBrowser().currentURI;
var domainloc = uri.host;
if (domainloc=="mysite.com"){
var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
httpChannel.setRequestHeader("x-test", "test", false);
}
}
},
register: function()
{
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.addObserver(this, "http-on-modify-request", false);
},
unregister: function()
{
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.removeObserver(this, "http-on-modify-request");
}
};
//register observer
httpRequestObserver.register();
};
exports.onUnload = function(reason) {
httpRequestObserver.unregister();
};
Please help me, I searched for hours with no results.
The code is working, but not at first time of page loading,
only if I reload.
The goal is that only on mysite.com, there will be a x-text=test header request, all the time, but only on mysite.com.
currentUri on browser is the Uri that is currently loaded in the tab. At "http-on-modify-request" notification time, the request is not sent to the server yet, so if it's a new tab, the browser doesn't have any currentUri. When you refresh the tab in place, it uses the uri of the current page, and it seemingly works.
Try this instead:
if (topic == "http-on-modify-request") {
var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
var uri = httpChannel.URI;
var domainloc = uri.host;
//only identify to specific preference domain
if (domainloc == "mysite.com") {
httpChannel.setRequestHeader("x-test", "test", false);
}
}
Related
I'm developing a plugin for Chrome and it has History feature in the plugin. For example, clicking the button creates a new tab and saves the URL address in the history. So this function works fine. But I want to get the document.title data of the tab that was opened in the past instead of the URL address. I tried doing this with tabs[tabs.length-1].title but it didn't get the title of the opened tab. Instead it got the title of the last tab that was already open. I guess this is the problem because the tab is not open yet. How can I solve this? Can you help me please?
This is my create tab function (If the tab is already open, don't open it again.):
function openTab(tab_url) {
var isTabActive = false;
var tabId = 0;
var tabTitle = "";
totalHistoryContent++;
chrome.tabs.query({}, function(tabs) {
for(var i=0;i<tabs.length;i++) {
if(tabs[i].url.toLowerCase().includes(tab_url.toLowerCase()) == true) {
isTabActive = true;
tabId = tabs[i].id;
tabTitle = tabs[i].title; // WORKING NICE
break;
}
}
if(isTabActive == false) {
chrome.tabs.create({ url:tab_url });
tabTitle = tabs[tabs.length - 1].title; // NOT WORKING CORRECTLY
} else{
chrome.tabs.update(tabId, {selected: true});
chrome.tabs.reload(tabId);
}
alert(tabTitle);
});
if(tab_url !== "chrome-extension://" + chrome.runtime.id + "/popup.html" && tab_url !== "chrome://extensions/?id=" + chrome.runtime.id) {
setHistory(tabTitle,49); //THIS FUNCTION SAVE TITLE TO HISTORY
}
}
One of the ways that you can handle this problem is sending an ajax request to the page's url
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'tab_url', true);
xmlHttp.onreadystatechange = function () {
if (
this.readyState == 4 &&
((this.status >= 200 && this.status < 300) ||
this.status == 304)
) {
var data = this.responseText;
var contentType = this.getResponseHeader("Content-Type"); //no i18n
if (contentType && contentType.match('text/html')) {
var doc = new DOMParser().parseFromString(data, "text/html");
console.log(doc.title);
}
}
};
xmlHttp.send();
Note: This may throw CORS error at most pages, so don't forget to add "<all_urls>" in permissions in manifest(assuming you are using manifest V2).
"permissions": [
"<all_urls>"
],
If you are using manifest V3, which is recommended, refer this documentation regarding permission
Other way is to send a message from chrome.tabs.create success callback to content script, if you don't use content script you have to inject code. In message response you can send the document's title using document.title.
Either way both will be asynchronous...
I'd like to know how to update URL addresses in Firefox using Web Extensions.
I'm trying to port a simple extension I've created with Chrome APIs to Firefox, but I don't really understand the tab URL mechanisms in Firefox.
This extension was made to switch between YouTube desktop/TV version with a click.
It works well on Chrome, but I don't know why it's not working on Firefox.
UPDATE 1: Placing most important code block related to the question:
chromeApi.browserAction.onClicked.addListener(function(tab) {
var actionUrl = '';
var tabUrl = tab.url;
if (getCurrentPageVersion(tabUrl) !== undefined) {
actionUrl = getConvertedActionUrl(tabUrl);
if (actionUrl !== tabUrl) {
chromeApi.tabs.update(tab.id, {url: actionUrl});
}
}
});
Full source
(function(chromeApi) {
getCurrentPageVersion = function (tabUrl) {
var ytValidRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)/g;
var ytValidStdPageRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)?(\/watch\?v=).+$/g;
var ytValidTvPageRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)?(\/tv#\/watch(\/video)?\/(idle|control)\?v=).+$/g;
if (!ytValidRegex.test(tabUrl)) {
return undefined;
} else if (ytValidStdPageRegex.test(tabUrl)) {
return "std";
} else if (ytValidTvPageRegex.test(tabUrl)) {
return "tv";
}
return undefined;
};
getConvertedActionUrl = function (tabUrl) {
var result = '';
var shortStdYtUrlRegex = /\/watch\?v=.+/g;
var shortTvYtUrlRegex = /\/tv#\/watch\/video\/(idle|control)\?v=.+/g;
var shortStdYtUrlReplaceRegex = /\/watch\?v=/g;
var shortTvYtUrlReplaceRegex = /\/tv#\/watch\/video\/(idle|control)\?v=/g;
if (shortStdYtUrlRegex.test(tabUrl)) {
result = tabUrl.replace(shortStdYtUrlReplaceRegex, '/tv#/watch/idle?v=');
}
else {
result = tabUrl.replace(shortTvYtUrlReplaceRegex, '/watch?v=');
}
// YouTube standard website video url
//https://www.youtube.com/watch?v=9tRDQK2MtRs
// YouTube TV url
//https://www.youtube.com/tv#/watch/video/idle?v=9tRDQK2MtRs
return result;
}
onInit = function () {
};
// Called when the user clicks on the browser action.
chromeApi.browserAction.onClicked.addListener(function(tab) {
var actionUrl = '';
var tabUrl = tab.url;
if (getCurrentPageVersion(tabUrl) !== undefined) {
actionUrl = getConvertedActionUrl(tabUrl);
if (actionUrl !== tabUrl) {
chromeApi.tabs.update(tab.id, {url: actionUrl});
}
}
});
chromeApi.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(!changeInfo.url) return; // URL did not change
// Might be better to analyze the URL to exclude things like anchor changes
var pageVersion = getCurrentPageVersion(tab.url);
if (pageVersion === undefined) return;
/* ... */
chromeApi.browserAction.setBadgeText({text: pageVersion.toUpperCase(), tabId: tab.id});
});
chromeApi.tabs.onCreated.addListener(function(tab){
var pageVersion = getCurrentPageVersion(tab.url);
if (pageVersion === undefined) return;
/* ... */
chromeApi.browserAction.setBadgeText({text: pageVersion.toUpperCase(), tabId: tab.id});
});
})(chrome);
If you pay attention, the core functionality happens on the chromeApi.browserAction.onClicked event, whenever you click the add-on/extension button.
The extension updates correctly between each YouTube version in Chrome, but in Firefox, this one redirects to YouTube TV once and never goes back to the desktop version no matter how many times you click on it.
But there's something weird in Firefox: browser history is updated correctly whenever the tab.update method is called, but it redirects to the TV version by itself again.
IMPORTANT: Both Firefox/Chrome extensions are using the currentTab permission, so it's not an extension issue by itself.
Extension on GitHub
UPDATE 2 (2018-11-25): I've updated the source code based on previous feedback
Is it possible to listen to the loading of images (or stylesheets) via the Mozilla Add-On SDK?
Having the user load a new URL can be found via the Page-Mod module, AJAX calls via overriding XMLHttpRequest.prototype.*().
Yet both only listen to loading of entirely new pages, not to the attached images of a page. Also, the image source might be changed for example in Javascript.
(It might be possible to use a http-on-modify-request, as pointed to here, but how can you access the nsIHttpChannel's URL and parameters?)
You can listen to every network request via
var {Cc, Ci} = require("chrome");
var httpRequestObserver = {
observe: function(subject, topic, data) {
if (topic == "http-on-modify-request") {
var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
var myURL = httpChannel.URI.spec;
console.log("url: " + myURL);
}
},
register: function() {
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.addObserver(this, "http-on-modify-request", false);
},
unregister: function() {
var observerService = Cc["#mozilla.org/observer-service;1"]
.getService(Ci.nsIObserverService);
observerService.removeObserver(this, "http-on-modify-request");
}
};
httpRequestObserver.register();
exports.onUnload = function(reason) {
httpRequestObserver.unregister();
};
See also Firefox Addon observer http-on-modify-request not working properly.
URI access
The nsIHttpChannel extends nsIChannel, which has a URI Attribute of type nsIURI, which has a spec attribute that contains the whole URL (including schema, parameters, ref, etc).
Trying to have a webpage manage a redirect, if a deeplink fails to open. If the deeplink opens, great. if it doesn't within 2 seconds, I want it to go to my website.
<script type="javascript">
setTimeout(function () { window.location = "http://mywebsite.com"; }, 25);
window.location = "my://app";
</script>
I've tested in Chrome and it works, but Firefox, IE, and Safari all block the script.
Anyone have any idea on how to handle this?
window.location.assign("http:mywebsite.com") may be a better alternative as I believe calling that function fires some additional events that may make the lifecycle of the page easy to manage.
Also in about all except Chrome you can use an IFrame to attempt to launch your protocol handler. This will help prevent the page going to about:blank and/or your script stopping due to navigating away from the page.
var createIframe = function(id, url, timeout, callback) {
var iframe;
iframe = document.createElement("iframe");
iframe.hidden = true;
iframe.id = id;
iframe.src = url;
var data = {}
data.id = id;
data.iframe = iframe;
return setTimeout(callback, timeout, null, data);
}
createIframe('tempFrame', 'http://mywebsite.com', 25, function(err, data) {
if(!err && data){
var iframe = data.iframe;
var id = data.id;
iframe = document.getElementById(id);
iframe.parent.removeChild(iframe);
}
else {
console.log('There was an error createing and removeing the iframe');
}
}
I am trying to display a 'mask' on my client while a file is dynamically generated server side. Seems like the recommend work around for this (since its not ajax) is to use an iframe and listen from the onload or done event to determine when the file has actually shipped to the client from the server.
here is my angular code:
var url = // url to my api
var e = angular.element("<iframe style='display:none' src=" + url + "></iframe>");
e.load(function() {
$scope.$apply(function() {
$scope.exporting = false; // this will remove the mask/spinner
});
});
angular.element('body').append(e);
This works great in Firefox but no luck in Chrome. I have also tried to use the onload function:
e.onload = function() { //unmask here }
But I did not have any luck there either.
Ideas?
Unfortunately it is not possible to use an iframe's onload event in Chrome if the content is an attachment. This answer may provide you with an idea of how you can work around it.
I hate this, but I couldn't find any other way than checking whether it is still loading or not except by checking at intervals.
var timer = setInterval(function () {
iframe = document.getElementById('iframedownload');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// Check if loading is complete
if (iframeDoc.readyState == 'complete' || iframeDoc.readyState == 'interactive') {
loadingOff();
clearInterval(timer);
return;
}
}, 4000);
You can do it in another way:
In the main document:
function iframeLoaded() {
$scope.$apply(function() {
$scope.exporting = false; // this will remove the mask/spinner
});
}
var url = // url to my api
var e = angular.element("<iframe style='display:none' src=" + url + "></iframe>");
angular.element('body').append(e);
In the iframe document (this is, inside the html of the page referenced by url)
window.onload = function() {
parent.iframeLoaded();
}
This will work if the main page, and the page inside the iframe are in the same domain.
Actually, you can access the parent through:
window.parent
parent
//and, if the parent is the top-level document, and not inside another frame
top
window.top
It's safer to use window.parent since the variables parent and top could be overwritten (usually not intended).
you have to consider 2 points:
1- first of all, if your url has different domain name, it is not possible to do this except when you have access to the other domain to add the Access-Control-Allow-Origin: * header, to fix this go to this link.
2- but if it has the same domain or you have added Access-Control-Allow-Origin: * to the headers of your domain, you can do what you want like this:
var url = // url to my api
var e = angular.element("<iframe style='display:none' src=" + url + "></iframe>");
angular.element(document.body).append(e);
e[0].contentWindow.onload = function() {
$scope.$apply(function() {
$scope.exporting = false; // this will remove the mask/spinner
});
};
I have done this in all kinds of browsers.
I had problems with the iframe taking too long to load. The iframe registered as loaded while the request wasn't handled. I came up with the following solution:
JS
Function:
function iframeReloaded(iframe, callback) {
let state = iframe.contentDocument.readyState;
let checkLoad = setInterval(() => {
if (state !== iframe.contentDocument.readyState) {
if (iframe.contentDocument.readyState === 'complete') {
clearInterval(checkLoad);
callback();
}
state = iframe.contentDocument.readyState;
}
}, 200)
}
Usage:
iframeReloaded(iframe[0], function () {
console.log('Reloaded');
})
JQuery
Function:
$.fn.iframeReloaded = function (callback) {
if (!this.is('iframe')) {
throw new Error('The element is not an iFrame, please provide the correct element');
}
let iframe = this[0];
let state = iframe.contentDocument.readyState;
let checkLoad = setInterval(() => {
if (state !== iframe.contentDocument.readyState) {
if (iframe.contentDocument.readyState === 'complete') {
clearInterval(checkLoad);
callback();
}
state = iframe.contentDocument.readyState;
}
}, 200)
}
Usage:
iframe.iframeReloaded(function () {
console.log('Reloaded');
})
I've just noticed that Chrome is not always firing the load event for the main page so this could have an effect on iframes too as they are basically treated the same way.
Use Dev Tools or the Performance api to check if the load event is being fired at all.
I just checked http://ee.co.uk/ and if you open the console and enter window.performance.timing you'll find the entries for domComplete, loadEventStart and loadEventEnd are 0 - at least at this current time:)
Looks like there is a problem with Chrome here - I've checked it on 2 PCs using the latest version 31.0.1650.63.
Update: checked ee again and load event fired but not on subsequent reloads so this is intermittent and may possibly be related to loading errors on their site. But the load event should fire whatever.
This problem has occurred on 5 or 6 sites for me now in the last day since I noticed my own site monitoring occasionally failed. Only just pinpointed the cause to this. I need some beauty sleep then I'll investigate further when I'm more awake.