Firefox web extension override newtab page - javascript

I'm trying to do something like this in my webextension inside background script for firefox 52 browser :
Components.utils.import("resource:///modules/NewTabURL.jsm");
NewTabURL.override(value);
But firefox says that Components.utils - undefined .
My extension based on chrome , so i need to use web extension addon type (.
Is it possible to override newtab page in other way before Firefox 54 realize ?
Update : here is my little code which helps me did newtab replace , but it buggy (
var newTabUrl = browser.extension.getURL("../index.html");
function handleActivated(activeInfo) {
console.log("Tab ", activeInfo);
if (activeInfo.url === "about:newtab") {
browser.tabs.update(activeInfo.id, {
url: newTabUrl
});
}
}
var querying = browser.tabs.query({
currentWindow: true,
active: true
});
const newtabdemo = {
getActiveTab: function() {
return browser.tabs.query({
active: true,
currentWindow: true
});
},
openNewTabPage: function() {
newtabdemo.getActiveTab().then((tab) => {
var gettingInfo = browser.tabs.get(tab[0].id);
gettingInfo.then(handleActivated);
});
}
};
browser.tabs.onCreated.addListener(newtabdemo.openNewTabPage);

You can create chrome override page for the newtab page.
https://developer.chrome.com/extensions/override
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/chrome_url_overrides
Example:
"chrome_url_overrides" : {
"newtab": "my-new-tab.html"
}

Related

Chrome extension ExecuteScript not firing XRM JavaScript

Dynamics CRM has its own XRM JS APIs, Which I'm trying to execute in a chrome extension that I'm working on. I'm using the below code.
chrome.tabs.query({ currentWindow: true, active: true }, function(tabs) {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: () => {
Xrm.Utility.alertDialog("Hello world", () => { });
}
});
});
Xrm.Utility.alertDialog("Hello world", () => { });
This code just shows a message box on the Dynamics CRM screen using this Dynamics API method.
If I run this code in the chrome console, it shows the message properly. If I just put alert("Hello world")", that code also runs which confirms that executeScript is working fine, but somehow Xrm isn't available.
Manifest.json
After overflowing the stack a few times, I learned that the script injection needs to happen by explicitly creating a script tag and injecting it on the page body. similar to the code below.
function runOnXrmPage() {
// create a script tag
var s = document.createElement('script');
s.src = chrome.runtime.getURL('webscript.js');
s.onload = function () {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
}
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: () => {
runOnXrmPage();
}
});
});
All the Xrm code was placed in webscript.js file and manifest was updated as pasted below.
"web_accessible_resources": [
{
"resources": [ "webscript.js" ],
"matches": [ "https://*.crm.dynamics.com/*" ]
}
]

How to detect when the Chrome browser window is closed using JavaScript?

I am trying to detect the following scenarios:
User navigates away from the web page
User closes the tab
User opens a new tab (i.e. visibility is lost on the old tab)
User closes the browser
I am able to detect all four scenarios above in Safari, Firefox and Chrome, except for "User closes the browser" in Chrome (91.0.4472.114). Currently it does not emit an event which I am able to listen for.
This is my code:
window.onbeforeunload = function() {
// do something
}
window.addEventListener('pagehide', function() {
// do something
}, { capture: true, once: true });
window.addEventListener('unload', function() {
// do something
}, { capture: true, once: true });
window.addEventListener('beforeunload', function() {
// do something
}, { capture: true, once: true });
window.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
// do something
}
}, { capture: true} );
As far as I can tell, I'm checking everything, but maybe I'm missing something?
Thanks for your help.

How to get current tab URL using Manifest v3?

How do I get the URL of the current tab in the background service worker in MV3?
Here's what I have:
let currentURL;
chrome.action.onClicked.addListener(handleBrowserActionClicked);
chrome.commands.onCommand.addListener(function(command) {
console.log("Command:", command);
handleBrowserActionClicked();
});
function handleBrowserActionClicked() {
togglePlugin();
}
function togglePlugin() {
console.log("toggle plugin");
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { greeting: "activateFeedback" });
});
}
// Fires when the active tab in a window changes.
chrome.tabs.onActivated.addListener(function () {
console.log("TAB CHANGED")
//firstTimeRunning = true
//feedbackActivated = false
currentURL = getTab()
.then(console.log("Current URL: " + currentURL))
})
// Fired when a tab is updated.
chrome.tabs.onUpdated.addListener(function () {
console.log("TAB UPDATED")
currentURL = getTab() // line 32
.then(console.log("Current URL: " + currentURL))
})
async function getTab() {
let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(chrome.tabs[0].url); // line 38
return tab;
}
Right now the service worker is logging "Current URL: [object Promise]" instead of, for example, "https://www.google.com"
It is also giving an error in the console (see comments above for line numbers)
background.js:38 Uncaught (in promise) TypeError: Cannot read property 'url' of undefined
at getTab (background.js:38)
at background.js:32
I think it may be something to do with my limited knowledge of promises!
Please help.
Thank you in advance.
You function getTab seems not right, you are currently trying to query on the url. Not on the query options. The following function should work.
async function getTab() {
let queryOptions = { active: true, currentWindow: true };
let tabs = await chrome.tabs.query(queryOptions);
return tabs[0].url;
}
Also make sure you have the tabs permission.
In the listener you also don't use the correct async/promise method two examples using Promise.then and await.
Promise.then:
chrome.tabs.onUpdated.addListener(function () {
console.log("TAB UPDATED")
getTab().then(url => {
console.log(url);
})
})
await:
chrome.tabs.onUpdated.addListener(async function () {
console.log("TAB UPDATED")
let url = await getTab()
console.log(url)
})
For the "Error: Tabs cannot be queried right now (user may be dragging a tab)." error you can look at this answer, which suggest a small delay before querying the tab url.
const tab = (await chrome.tabs.query({ active: true }))[0]
Simply use "activeTab" permission in manifest.json
Add activeTab in your manifest.json.
"permissions": [
"activeTab",
],
And In Background.js
chrome.action.onClicked.addListener((tab) => {
console.log(tab.url);
});
I'm sure It will help you to get the current tab URL.
useful links - ActiveTab

chrome extension - issue with propertie "active" of chrome.tabs.create

I am creating a new tab and and injecting some code in it straight after.
But the problem is that the code to be injected is not injected properly when using the property active:true(which I need to use) on tabs.create.
Here is the code in popup.js:
chrome.tabs.create({url: "http://localhost:3000/", index: newTabId, active: false}, (newTab) => {
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// check status so that it sends only one message, and not one for each status change
if(changeInfo.status === "loading") {
if (tab.id === newTab.id) {
chrome.tabs.sendMessage(newTab.id, {message: "watch_video", videoData: selectedVideoData},
function (resp) {
console.log("Resp",resp);
return true;
}
);
}
}
});
})
Here is the problematic line: chrome.tabs.create({url: "http://localhost:3000/", index: newTabId, active: false}. When active is false, the code is injected, but when it is true, nothing seems to happen.
inject.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "watch_video") {
console.log("inject soon")
injectScript(request.videoData);
sendResponse("watch_video script is to be injected in " + window.location.href)
}
});
function injectScript(videoData) {
console.log("injected")
$(document).ready(function() {
document.test = "ABCDE"
const checkState = setInterval(() => {
$(".bkg").css({ "background-color": "#ffffff"})
}, 100)
})
}
Here I tried something with setInterval(), it does not work when active is true.
However it does work with a timeout. But does not not work without any timeout or interval when active is set to true.
I could use just use a timeout, but it is not really clean, I would prefer to understand why it behaves like it does. I am using react btw.
Here is what it is said about the active property:
Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see windows.update). Defaults to true.
Source: https://developer.chrome.com/extensions/tabs#method-create

mozilla addon. required(sdk/tabs).attach() not working

I began to develop addon for firefox and I had a problem.
var tabs = require('sdk/tabs');
tabs.on('ready', function (tab) {
tab.attach({
contentScript: "alert('azaza');",
onMessage: function(message) {
console.log("message");
}
});
})
When I try to execute this code in Firefox nightly 36 it says "TypeError: window is null", but in Nightly 32 it works fine! In last fierfox (not nightly) this code not working too.
I tried to execute this code in nightly's browser debugger console, but the same result (window is null).
I can see, that in sdk/tabs/utils.js browser.contentWindow is null. I think this is my window object, but why it is null?
I was able to reproduce this issue with the following code:
var { ActionButton } = require("sdk/ui/button/action");
var self = require("sdk/self");
var tabs = require('sdk/tabs');
var button = ActionButton({
icon: self.data.url("icon-16.png"),
id: "my-button",
label: "my button",
onClick: function() {
tabs.open({
url: self.data.url("text-entry.html")
});
tabs.activeTab.attach({
contentScript: "alert('azaza');"
});
}
});
To fix this issue I had to use onOpen instead of using activeTab:
var button = ActionButton({
icon: self.data.url("icon-16.png"),
id: "my-button",
label: "my button",
onClick: function() {
tabs.open({
url: self.data.url("text-entry.html"),
onOpen: function() {
tabs.activeTab.attach({
contentScript: "alert('azaza');"
});
}
});
}
});
Perhaps are you using the attach method when you cannot use it?

Categories

Resources