Chrome Extension Redirection - google-chrome

Hi i did a Chrome extension who block urls, actually when a url is blocked a white page come and show a messagen i would like to do a redirection instead to google.com.
this is my actual code of background.js:
(function() {
var AUTHORIZED_DOMAINS= {
"www.badurl.com": false,
"badurl.com": false
};
function extract_domain(url) {
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
return matches[1];
}
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var domain = extract_domain(details.url);
return { cancel: AUTHORIZED_DOMAINS[domain ]===false };
}, {urls: ["<all_urls>"]},["blocking"]);})();

instead of returning { cancel: ... } in the listener, let's just use the tabs API:
chrome.tabs.update({
url: "http://www.google.com/"
});
Note: tabs permission is required

Related

Chrome Extension embedding script in active web page, in MV3?

beautiful people on the internet. I am new to chrome extension not new to writing code though. I have implemented webpack to use external packages. One major one in my application is npm package by the name "mark.js".
My application works like this i want some specific words to be highlighted in active webpage using this package. I have written code for this to achieve the functionality but the problem is with loading the script in a web page. I have performed different aspect of loading script but that doesnot work. The new MV3 version have some strict rules.
I want to achieve anything similar of loading script in an active webpage. Please help.
btn.addEventListener("click", async () => {
console.log("BUTTON IS PRESSED!!");
try {
await chrome.tabs.query(
{ active: true, currentWindow: true },
async function (tabs) {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: highlightText,
args: [arr],
});
}
);
} catch (e) {
console.log("ERROR AT CHROME TAB QUERY : ", e);
}
});
async function highlightText(arr) {
console.log(typeof Mark);
try {
var instance2 = new Mark(document.querySelector("body"));
// instance2.mark("is");
var success = [];
// const instance2 = new Mark(document.querySelector("body"));
await Promise.all(
arr.map(async function (obj) {
console.log("OBJECT TEXT : ", obj.text);
instance2.mark(obj.text, {
element: "span",
each: function (ele) {
console.log("STYLING : ");
ele.setAttribute("style", `background-color: ${obj.color};`);
if (obj.title && obj.title != "") {
ele.setAttribute("title", obj.title);
}
ele.innerHTML = obj.text;
success.push({
status: "Success",
text: obj.text,
});
},
});
})
);
console.log("SUCCESS : ", success);
} catch (error) {
console.log(error);
}
}
There's no need to use chrome.runtime.getURL. Since you use executeScript to run your code all you need is to inject mark.js before injecting the function.
Also, don't load popup.js in content_scripts, it's not a content script (these run in web pages), it's a script for your extension page. Actually, you don't need content_scripts at all.
btn.addEventListener('click', async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const target = { tabId: tab.id };
const exec = v => (await chrome.scripting.executeScript({ target, ...v }))[0].result;
if (!await exec({ func: () => !!window.Mark })) {
await exec({files: ['mark.js.min'] });
await exec({func: highlightText, args: [arr] });
}
});
For V3 I assume you will want to use Content Scripts in your manifest to inject the javascript into every webpage it matches. I recently open-sourced TorpedoRead and had to do both V2 and V3, I recommend checking the repo as it sounds like I did something similar to you (Firefox is V2, Chrome is V3).
The code below need to be added to your manifest.json and this will execute on every page based on the matches property. You can read more about content scripts here: https://developer.chrome.com/docs/extensions/mv3/content_scripts/
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["yourscript.js"]
}
],

Unable navigate to new tab on click of mouse middle button/ ctrl+ click in angular js

Currently i am using angular 1.6 application
I implemented this code from stackoverflow but this is not solving my solution.
this is my code below
app.run(function($rootScope, $state) {
$rootScope.navigate = function($event, to, params) {
// If the command key is down, open the URL in a new tab
if ($event.metaKey) {
var url = $state.href(to, params, {absolute: true});
window.open(url,'_blank');
} else {
$state.go(to, params);
}
};
});
My HTML code
<div class="title" data-ng-click="$ctrl.goToDetails($event)" data-ng-bind="$ctrl.config.entryTitle"></div>
Controller
$state.go('entry-details', { entryId: vm.config.id, query: vm.query });
I am new to angular so please suggest how to implement.
it would be better if i get a fiddle.
All you need in your code is: absolute: false and call the function navigate with ng-click, below is tested example. it works fine:
app.run(function($rootScope, $state,$window) {
$rootScope.navigate = function($event, to, params) {
// If the command key is down, open the URL in a new tab
if ($event.ctrlKey) {
var url = $state.href(to, params, {absolute: false});
$window.open(url,'_blank');
} else {
$state.go(to, params);
}
};
})
<div ng-click="navigate($event, 'StateName', {PARAMS:PARAMS})">ClickMe</div>

Getting chrome.getAuthToken to work inside a script

I'm building a Chrome extension that retrieves data from a user's Google Drive and inserts it into an arbitrary page. I've gotten the OAuth to work, but I can't seem to get access to the token (which I can see is set via chrome://identity-internals).
The issue here is that when the Chrome extension nav bar button is clicked, I fire a request to execute test.js. test.js apparently has no concept of chrome.identity, but it needs that information to make an XHR request. I've tried
Storing the auth token in localStorage so that test.js can retrieve it (no luck)
Nesting the test.js inside the AuthToken request (not sure how to actually pass the variable into the file and retrieve it).
Are there any ideas?
Thank you in advance!
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
// This works
alert(token);
// This doesn't work
localStorage.setItem("authtoken", token);
});
chrome.tabs.executeScript(tab.id, {
// This file needs access to the authtoken
// but within test.js, chrome.identity is undefined.
"file": "test.js"
}, function () {
});
});
localStorage (effectively it's window.localStorage) is stored per origin (scheme + hostname + port number), and extensions have their own one in privileged components that can access restricted chrome.* API (some are listed as exceptions in content scripts docs), namely popup and background/event page, options, and other pages with a URL like chrome-extension://abc..... (abc... is an extension ID).
localStorage of a web page belongs to its own origin such as https://www.google.com.
Content scripts run in the context of web page, so they can't access extension's localStorage directly. They see localStorage of their web page's origin only.
Solution 1: use another executeScript to set a variable that will be used by the content script injected from a file:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.identity.getAuthToken({interactive: true}, function(token) {
chrome.tabs.executeScript(tab.id, {
code: 'var token=' + JSON.stringify(token) + ';'
}, function() {
chrome.tabs.executeScript(tab.id, {file: "test.js"}, function() {
});
});
});
});
JSON-serialization is used in order not to bother escaping special characters and be able to pass objects.
Solution 2: use messaging API to pass data once the content script is injected:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.identity.getAuthToken({interactive: true}, function(token) {
chrome.tabs.executeScript(tab.id, {file: "test.js"}, function() {
chrome.tabs.sendMessage(tab.id, {token: token});
});
});
});
content script:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.token) {
document.getElementById('token').textContent = msg.token;
//nowYouCanProcessToken(msg.token);
}
});
Solution 3: use chrome.storage API accessible both from a content script and the abovementioned privileged parts of an extension.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.identity.getAuthToken({interactive: true}, function(token) {
chrome.storage.local.set({token: token}, function() {
chrome.tabs.executeScript(tab.id, {file: "test.js"}, function() {
});
});
});
});
content script:
chrome.storage.local.get('token', function(data) {
if (data.token) {
document.getElementById('token').textContent = data.token;
//nowYouCanProcessToken(data.token);
}
});

how to change the popup content based on the current url extension page action

am new in creating chrome extensions, I'm developing an extension page action it works in certain urls, I would like to put different text in the popup for each url, i can do it? please help me.
My background.js is thus
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (~tab.url.indexOf('url1.com.br')) {
chrome.pageAction.show(tabId);
}
if (~tab.url.indexOf('url2.com.br')) {
chrome.pageAction.show(tabId);
}
});
OK. First of all, to show page_action icon on specific URLs you can use declarative content.
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's on a specific URL
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'url1.com.br' },
}),
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'url2.com.br' }
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
Don't forget adding a permission for declarative content in manifest.json. Another thing is different texts for different urls.
popup.js
chrome.tabs.query({'active': true, 'currentWindow': true}, function (tabs) {
var dynamicText = "You are here;"+ tabs[0].url;
document.getElementById("textbox").value = dynamicText ;
});
This sample gets the currentWindow's URL and insert it into the element that has textbox id. I hope samples are enough to solve the problem.

Cannot view source HTML on Chrome

I am unable to view the HTML content of web pages when I view source in Google Chrome's dev tools. For example, if I view the source of https://stackoverflow.com/help, the only content I can see is as follows.
<script>
$('#herobox li').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("aboutpage.click", { aboutclick_location: "hero" }, true);
});
window.location.href = '/about';
});
$('#tell-me-more').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("aboutpage.click", { aboutclick_location: "hero" }, true);
});
});
$('#herobox #close').click(function () {
StackExchange.using("gps", function () {
StackExchange.gps.track("hero.action", { hero_action_type: "minimize" }, true);
});
$.cookie("hero", "mini", { path: "/" });
$.ajax({
url: "/hero-mini",
success: function (data) {
$("#herobox").fadeOut("fast", function () {
$("#herobox").replaceWith(data);
$("#herobox-mini").fadeIn("fast");
});
}
});
return false;
});
</script>
I'm not sure if I've inadvertently changed a setting in Chrome, but any help would be greatly appreciated.
I'm using chrome Version 29.0.1547.76.
I have disabled all extensions.
I tried this using a new profile with the same effect.
I'm not behind a proxy.
If you open the DevTools after loading the page, the content of the items listed on the Resources tab may not be populated. This is also true of network requests on the Network tab. To see the fully populated resources on the Resources tab, first open the DevTools, then refresh the page, or navigate to the desired page with the DevTools open. Now select the html resource and it should be populated.