I am writing a chrome extension to allow users to login to social media sites from a single page. I am able to create a new incognito window but am unable to manipulate anything inside of the window that I created. I want to create an onload function for the new window to execute jquery. Thanks for getting me pointed in the right direction!
Refer the following demonstration for manipulation of new incognito window created and injecting some jquery into it.
References
Windows API
Tabs API
Background Pages
Content Scripts
Manifest file.
manifest file
This is used to bind permissions and register background pages to extension.Ensure it has all permissions needed.
{
"name":"Hanlder for Incognito window",
"description":"http://stackoverflow.com/questions/14044338",
"version":"1",
"manifest_version":2,
"background":{
"scripts":["background.js"]
},
"permissions":["tabs","http://www.google.co.in/"]
}
background.js
Inject jquery into new incognito window, from background page.
var _tabId_To_Look_For;
// Create a new incognito Window with some arbitary URL and give it focus
chrome.windows.create({
"url": "http://www.google.co.in/",
"focused": true,
"incognito": true
}, function (window) {
// Trace tab id which is created with this query
_tabId_To_Look_For = window.tabs[0].id
});
// Add an event Listener for new tab created
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
// Inject script into chosen tab after it is loaded completely
if (tabId == _tabId_To_Look_For && changeInfo.status == "complete") {
// Inject Jquery and in current tab
chrome.tabs.executeScript(tabId, {
"file": "jquery.js"
}, function () {
// I am in call back
console.log("Injected some jquery ");
});
}
});
Ensure you have enabled incognito access.
Output
You will observe a new window with jquery injected.
Related
I am creating a chrome extension which embeds an iframe on a website and it works well except when a user clicks on the iframe (or anything inside the iframe) and then tries to use the back button to navigate back to a previous page on the parent/actual site. When you attempt to go back the page just reloads the iframe (even when you press the back button many times, each time it just reloads the iframe). If the user doesn't click on the iframe (just mouseover) everything works as expected. Here is what my chrome extension is doing:
background.js:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status == 'complete') {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: createIframe
});
}
});
function createIframe() {
var location = document.getElementById(id of location);
var embed = document.createElement("iframe");
embed.setAttribute('src', link);
location.appendChild(embed.cloneNode(true));
}
Responses to similar problems said the issue was setting the src link using setAttribute and that this method added the iframe loading to the browser history. To fix this they suggest using iframe.contentWindow.location.replace(link);. I tried doing this, but the iframe didn't even load the link content (not sure if replace requires a location to be set already):
embed.setAttribute('id', 'uniqueid');
var frame = document.getElementById('uniqueid');
frame.contentWindow.location.replace(link);
I am new to web development (and chrome extension development) and any help would be greatly appreciated! Thanks in advance.
I am trying to make a simple chrome extension.
It is supposed to add an item "Open new tab" in the 'windows system tray chrome icon context menu' (similar to how the checker plus for gmail extension has done; see the second image given below).
when I click the option, chrome is supposed to (check if any window is open. If yes, then it is supposed to) open a new tab page. If no windows are open, then it is supposed to open a new chrome window with the new tab page showing.
What I have done till now:
manifest.json
{
"manifest_version": 2,
"name": "Open New Tab",
"description": "This extension open a new tab page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png"
},
"background":{
"scripts":["background.js"],
"persistent": false
},
"permissions": [
"background",
"activeTab"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab)
{
chrome.tabs.create({ url: "chrome://newtab" });
}
);
background.html
<html>
<head>
<script>
chrome.browserAction.onClicked.addListener(function(window)
{
chrome.windows.create({url: "chrome://newtab", type: "normal"});
}
);
</script>
</head>
</html>
I have already loaded this extension.
The effects of my extension on chrome so far:
1) Chrome window is already open.
My icon shows up in the list of extensions and is clickable.
On clicking, a 'new tab' page is opened in the same window. This is correct. (Though I don't need this. For now, let it be.)
2) Chrome window is closed, and chrome is allowed to run in the background. Rightclick the chrome tray icon. My extension menu 'Open a new tab' shows up in the menu.
This is also correct. On clicking it, a new chrome window is created. (Currently, I have not yet checked if a window already exists. That is to come later.).
The problem is that, in the new window that opens, instead of the 'new tab' page, chrome automatically opens the 'chrome://extensions' URL. This is wrong, and I cannot understand why the extensions page is opening. I want to open the new tab page, and i am passing the 'chrome://newtab' URL. How do I make chrome open the new tab page from here? Chrome works correctly when I start it from my desktop icon or windows start menu. So, the problem seems to be something with my code.
Any help is appreciated.
Listen to chrome.windows.onCreated event, when right clicking chrome tray icon, a new window would be launched, then you could create a new tab in the event handler.
chrome.windows.onCreated.addListener(function(window) {
chrome.windows.getAll(function(windows) {
if (windows.length === 1) {
chrome.tabs.create({windowId: window.id, url: "chrome://newtab"});
}
});
});
I've written a Chrome extension that overrides the New Tab page:
manifest.json:
"chrome_url_overrides": {
"newtab": "new-tab.html"
},
Is there a way to make this override optional? That is, I'd like to enable the user to uncheck a checkbox in the options page and disable the New Tab override. This must be possible because when I open a new tab for the first time, there's a popup informing of an extension changing the New Tab settings and asking whether to keep changes or restore settings:
I couldn't find any API for controlling overrides. The New Tab Redirect project doesn't have an option to display the native New Tab.
Google made a Star Wars new tab replacement which allows you to view the default new tab page. The url it uses is chrome-search://local-ntp/local-ntp.html.
Example:
options.html:
<input type="checkbox"> Use default new tab page
options.js:
var checkbox = document.querySelector("input[type=checkbox]")
checkbox.addEventListener("click", function() {
chrome.storage.sync.set({ defaultnewtab: checkbox.checked })
})
newtab.js:
chrome.storage.sync.get("defaultnewtab", function(storage) {
if(storage.defaultnewtab) {
chrome.tabs.update({ url: "chrome-search://local-ntp/local-ntp.html" })
}
})
Instead of using the chrome_url_override you could write a listener that listens for when tabs update using the chrome.tabs.onUpdated.addListener(), then check if the url is chrome://newtab/ and if it is and the check box is ticked, then using chrome.tabs.update() relocate them to another page.
Using the Star Wars method as described #Daniel Herr, I did this, which is working well. Although feels a little hack-y.
I have an option being set in the popup.html whether the Extension is "on" or not.
First off, set the default new tab page using the Chrome defined method:
manifest.json
"chrome_url_overrides": {
"newtab": "newtab.html"
},
Then in your Extension's newtab.html call a new JavaScript file, newtab.js (or whatever).
I am also using jQuery, so my code uses that, but you can do this natively using DOMContentLoaded.
newtab.js
$(document).ready(function(){
// It takes a moment for the Chrome query/update so sometimes there is a flash of content
// Hiding the Body makes it look blank/white until either redirected or shown
$('body').hide();
var background = chrome.extension.getBackgroundPage();
var _app = background._app;
// App is OFF, show Default New Tab
if(!_app._on){
// Get the current Tab
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
var active = tabs[0].id;
// Set the URL to the Local-NTP (New Tab Page)
chrome.tabs.update(active, { url: "chrome-search://local-ntp/local-ntp.html" }, function() { });
});
// App is ON, show custom content
} else {
$('body').show();
}
});
Basically, the methodology is to update the Tab so that it is redirected to chrome-search://local-ntp/local-ntp.html which is the hard URL to the default Chrome NTP.
Since this is a Chrome internal URL -- the URL field still appears blank.
I want to access the properties of a window object from a background script. I have this in manifest.json:
{
"..": "..",
"permissions": ["http://*.mysite.net/"],
"background": {
"scripts": ["extension.js"]
}
}
and this in extension.js:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
var tabWindowObject = ??
setInterval(tabWindowObject.someFunction, 10);
}
});
I need it here, not in another place (no content scripts and no script injection). How do I get the tabWindowObject in extension.js? In other words, I want to access the context of a tab inside a background script Chrome extension.
You can't. The extension's background page runs in one process, while the tab that was updated runs in a separate process. Different processes can't share objects, so you can't directly access the window object of a tab from an extension's background page. You have to use a content script to get extension code to run inside the tab's process.
I am writing a Chrome extension, and I want a login window to be popped up when users click on the context menu so that user can input username and password. In Chrome extension, I only found chrome.pageAction.setPopup and chrome.browserAction.setPopup can be used to show popup windows, but they show popups only when the page action's icon or browser action's icon is clicked, not the context menu. Of course, I can use javascript prompt box to do this, but the problem is the password cannot be masked in the prompt box. So I am wondering if there are some other ways to create a popup window in Chrome extension.
Thanks!
Pick and choose:
showModalDialog(<String url> [, <object arguments>])
Opens a dialog-like window, in which you can load a page within your chrome extension. HTML can be used.
Do not use showModalDialog, it is going to be removed from Chrome.
window.open(<String url> [, <String window_name>[, <String windowFeatures>]])
Opens a window, which, unlike the previous method, does not appear as a dialog. The user can minimize the window, and continue with something else.
chrome.windows.create(<object createData [, <function callback>]>)
(Specific to Chrome extensions) Create a new window, with given arguments (size, url, position, ...).
All of these methods allows you (your extension) to open a new window/dialog, and handle the logic from that page. This page should be packaged with your extension.
See Message passing to pass the entered data to your extension.
Demo
Tabs within your extension have direct access to the background page using chrome.runtime.getBackgroundPage. I'll demonstrate this feature in this demo, as well as a conventional way of message passing:
manifest.json
{
"name": "Dialog tester",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["open-dialog.js"]
}]
}
background.js
// Handle requests for passwords
chrome.runtime.onMessage.addListener(function(request) {
if (request.type === 'request_password') {
chrome.tabs.create({
url: chrome.extension.getURL('dialog.html'),
active: false
}, function(tab) {
// After the tab has been created, open a window to inject the tab
chrome.windows.create({
tabId: tab.id,
type: 'popup',
focused: true
// incognito, top, left, ...
});
});
}
});
function setPassword(password) {
// Do something, eg..:
console.log(password);
};
open-dialog.js
if (confirm('Open dialog for testing?'))
chrome.runtime.sendMessage({type:'request_password'});
dialog.html
<!DOCTYPE html><html><head><title>Dialog test</title></head><body>
<form>
<input id="pass" type="password">
<input type="submit" value="OK">
</form>
<script src="dialog.js"></script>
</body></html>
dialog.js
document.forms[0].onsubmit = function(e) {
e.preventDefault(); // Prevent submission
var password = document.getElementById('pass').value;
chrome.runtime.getBackgroundPage(function(bgWindow) {
bgWindow.setPassword(password);
window.close(); // Close dialog
});
};
Documentation for used methods
chrome.runtime.sendMessage(<request>, <function callback>) and chrome.runtime.onMessage.addListener(<function listener>)
chrome.extension.getURL(<String path>)
chrome.runtime.getBackgroundPage(<function callback>)
chrome.tabs.create(<object createData> [, <function callback>])
chrome.windows.create(<object createProperties> [, <function callback>])