Getting current tab url in chrome extension - google-chrome-extension

Duplicate of Display current URL in a chrome extension
The solution in my 'background.js':
$(document).ready(function(){
chrome.tabs.query({'active': true, 'lastFocusedWindow': true, 'currentWindow': true}, function (tabs) {
var url = tabs[0].url;
console.log(url);
alert(url)
})
})
did not work for me.
I also gave 'tabs' permission on manifest.json
{
"manifest_version": 2,
"name": "YtDl",
"version": "0.1",
"permissions": ["tabs"],
"background": {
"persistent": false,
"scripts": ["jquery.min.js", "background.js"]
},
"content_scripts":[
{
"matches": ["<all_urls>"],
"js": ["jquery.min.js", "content.js"],
}
]
}
is there any other solution to get current tab url?
NOTE: I am trying to get URL from background script. when i reload the extension it works for one time in 'chrome://extensions/' and does not work at any other site.

Related

Chrome and closing a specific tab URL

I need to close a specific tab in Google Chrome.
The behaviour is that an extension open up URL after she loaded and this can't be avoid.
This doesn't work :
#manifest.json
{
"name": "Close Tab Helpx Adobe",
"description": "Close the url http://www.example.com",
"version": "0.1",
"manifest_version": 2,
"app": {
"background": {
"scripts": ["background.js"],
"persistent": false
}
},
"icons": {
"16": "close-tab-helpx-adobe-16.png",
"128": "close-tab-helpx-adobe-128.png"
},
"permissions": [
"tabs"
]
}
#background.js
chrome.tabs.onUpdated.addListener(function(tab) {
if(tab.url=="http://www.example.com") {
chrome.tabs.remove(tab)
}
});
In developper mode, i can see Uncaught TypeError: Cannot read property 'onUpdated' of undefined
As you can see, i'm a beginner.
Do you know how to achieve this ?
EDIT:
I also tried :
#background.js
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.get(activeInfo.tabId, function(tab){
if(tab.url=="http://www.example.com") {
chrome.tabs.remove(tab);
}
});
});
chrome.tabs.getCurrent(function(tab){
if(tab.url=="http://www.example.com") {
chrome.tabs.remove(tab);
}
});
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
if(tabs[0].url=="http://www.example.com") {
chrome.tabs.remove(tabs[0]);
}
});
The error is the same, only the property name change onActivated, getcurrent or query
Thanks to wOxxOm (and his patience), here is a code which do the job :
#manifest.json
{
"name": "Close Tab Helpx Adobe",
"description": "Close the url http://www.example.com",
"version": "0.1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"icons": {
"16": "close-tab-helpx-adobe-16.png",
"128": "close-tab-helpx-adobe-128.png"
},
"permissions": [
"tabs"
]
}
#background.js
chrome.tabs.onCreated.addListener(function(tab) {
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(tab.url=="http://www.example.com") {
chrome.tabs.remove(tab.id);
}
});
});
So, i have my answer.
To go further ...
Haibara Ai says "Please be aware chrome.tabs.onUpdated will also fired for iframes, if a page contains many iframes, each completed iframe will trigger the event though you have checked : https://stackoverflow.com/a/36818991/2241806"

In Chrome Extension,How to prevent page redirect when <a> tag is clicked

I have a chrome extension.
What I want to is :
When an <a> tag is clicked in a page (named A) , I use chrome.webRequest.onBeforeRequest to block the request.
The question is:
I tried both {redirectUrl: 'javascript:'} and {cancel: true}, but the page A still redirect.
How can I prevent the redirect in chrome extension.
manifest.json:
{
"background": {
"page": "background.html"
},
"browser_action": {
"default_icon": "img/19.png",
"default_popup": "popup.html",
"default_title": "test"
},
"icons": {
"128": "img/128.png",
"48": "img/48.png"
},
"is_account_related": false,
"manifest_version": 2,
"minimum_chrome_version": "38.0.0.0",
"permissions": ["webRequest", "webRequestBlocking", "notifications", "tabs", "storage", "cookies", "http://*/*", "https://*/*", "*://*/*"],
"homepage_url": "xxxx",
"name": "test",
"description": "test",
"version": "10.3.6",
"content_security_policy": "script-src 'self' 'unsafe-eval' xxx 'unsafe-inline'; object-src 'self'",
"key": "xxx"
}
background.html
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
console.log('========start============');
console.log('block', details, details.url);
console.log('========end============');
// return { redirectUrl: 'javascript:' };
return { cancel: true };
},
{ urls: ["*://developer.mozilla.org/*"] },
['blocking']
);
In the background.html, the log is correct. But the page still navigate
=== update
I find that the page use history API to navigate. So is there any way to prevent history api, like history.push, history.replace ?
You could also return false; every time <a> clicked like this:
for(elem of document.getElementsByTagName("a")){
elem.onclick = () => false;
}
Make sure you have appropriate permissions in your manifest, as it is mentioned in the docs
As this function uses a blocking event handler, it requires the "webRequest" as well as the "webRequestBlocking" permission in the manifest file.
Also you can try something like
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return {cancel: true}; },
{urls: ["<all_urls>"]},
["blocking"]);

Chrome extension to redirect tab url

I am trying to create a chrome extension to redirect a tab url via a custom url. I browsed many already answered questions and tested many but did not find the answer.
my manifest:
{
"name": "Price saver",
"version": "1.0",
"manifest_version": 2,
"description": "Price saving during online shopping",
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2,
"permissions": ["tabs", "webRequest", "webRequestBlocking", "http://*/*", "https://*/*"]
}
my background.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
var currentUrl = tabs[0].url;
var newUrl = "www.dealtikka.com/out.php?url=" + currentUrl
return { redirectUrl: newUrl};
},
{
urls: [
'*://*.*/*'
],
types: ['main_frame']
},
['blocking']);
Nothing happens when I click the extension.

tabs.executeScript: Cannot access contents of url

Well, this code was working and now, not anymore, WHY? I'm just trying to inject code via content script. (base code)
manifest.json
{
"name": "Test",
"permissions": [
"activeTab"
],
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": [
"bower_components/jquery/dist/jquery.min.js",
]
}],
"browser_action": {
"default_icon": {
"19": "icon_19.png"
}
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {
file: "content_script.js"
});
});
I can suppose it's a permission bug. But, what should I add for this work ?
You have to add to your permissions the url of the page wich you want to inject your code.
If I well understand, you want to inject the code in the active tab, so you can use the activeTab permission that temporally give permission to your extension for the curent tab when the user invokes your extension (by clicking the browser action for example). You can read more about it here.

Running jquery script triggered by context menu in chrome extension

I am new to chrome extension development. The sample code I have is not running properly.
Requirement: Executing any jquery script(say $("body").hide();) on click of context menu button.
From the code, only jquery part is not working.
I have following files:
manifest.json
{
"manifest_version": 2,
"name": "jQuery DOM",
"version": "1",
"permissions": [
"contextMenus","tabs","activeTab"
],
"background": {
"scripts": ["jquery.min.js","sample.js"]
},
"description": "Manipulate the DOM when the page is done loading",
"browser_action": {
"name": "Manipulate DOM",
"icons": ["icon.png"],
"default_icon": "icon.png"
},
"content_scripts": [ {
"js": [ "jquery.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"],
"run_at": "document_end"
}]
}
background.js
$("body").append('Test');
I have icon.png in folder, and it gets loaded well.
jquery.min.js in same folder
sample.js
alert("Extension loaded");
function genericOnClick(info, tab) {
alert("Tab "+tab.id);
chrome.tabs.executeScript(tab.id, {
file: "jquery.min.js",
allFrames: true
},function(){
alert("callback");
$("body").hide();
});
alert("Completed");
$("body").hide();
}
var contexts = ["page"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Test Page menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
"onclick": genericOnClick});
console.log("'" + context + "' item:" + id);
}
background.js works!
All the alerts work file, but .hide function from genericOnClick doesn't work.
Even if I move the code from sample.js to backgroud.js, it won't work.
Can you please tell me where did i go wrong ?
As I mentioned, a background script isn't allowed to interact with the DOM, (while a content script isn't allowed to use chrome.contextMenus). You need to combine both, and use message passing to tell the content script when to execute. Some other adjustments I made:
I renamed background.js and content.js so that their names now
reflect what they do, and made background.js into an event page.
I removed the browser action (the
extension would need browserAction.html or background.js would
need chrome.browserAction.onClicked.addListener to do anything
other than show the icon).
Programmatically injecting jquery means that always loading it as a
content script is unnecessary (although skipping programmatic injection allows you to omit the last three permissions).
background.js doesn't need jquery
anymore, so it isn't loaded there either.
The default executeScript
tab is the active tab, so we don't need it's id.
Here's the finished product:
manifest.json
{
"manifest_version": 2,
"name": "jQuery DOM",
"version": "1",
"permissions": [
"contextMenus", "activeTab", "tabs", "http://*/", "https://*/"
],
"background": {
"scripts": [ "background.js" ],
"persistent": false
},
"content_scripts": [ {
"js": [ "content.js" ],
"matches": [ "<all_urls>" ]
}],
"description": "Manipulate the DOM when the page is done loading"
}
background.js
function genericOnClick(info, tab) {
chrome.tabs.executeScript(null,
{"file": "jquery.min.js"},
function() {
chrome.tabs.sendMessage(tab.id,{"message":"hide"});
});
}
chrome.contextMenus.create({"title": "Test Page menu item",
"contexts":["page"],
"id":"contextId"});
chrome.contextMenus.onClicked.addListener(genericOnClick);
content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.message == 'hide') {
$("body").hide();
}
sendResponse();
});
Your content.js is probably much larger than it is here (+1 for the SSCCE). But if it is small, another option would be to omit the content script entirely, and replace the sendMessage with chrome.tabs.executeScript(null,{code:"$('body').hide();"});.

Resources