Chrome Extension: Redirect at specific time - javascript

Hey trying to redirect from page1 to page2 (within tab, not open new ones) at a specific time.
manifest.json:
{
"name": "Google",
"description": "Test",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts":["script.js"]},
"permissions": [
"alarms",
"webRequest",
"*://www.google.com/*",
"webRequestBlocking"
]
}
script.js:
var host = "https://www.facebook.com/"
chrome.alarms.onAlarm.addListener(function(alarm){
return {redirectUrl: host}
})
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return chrome.alarms.create("redirect", {when: Date.now() + 5000})
},{
urls: [
"*://www.google.com/*"
],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
["blocking"]
)
code to redirect was taken from This Question,
code to use timer was taken from This Question
EDIT: Solution thanks to Xan's answer below
manifest.json
{
"name": "Google",
"description": "Test",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
"matches": ["*://www.google.com/*"],
"js": ["script.js"]
}]
}
script.js (modify setTimeout with Date.now() to get correct wait)
setTimeout(function() {
window.location = "https://www.facebook.com/"
}, 5000)

That won't work, and it's not what you want anyway.
chrome.webRequest.onBeforeRequest refers to what to decide regarding a network request before it's even sent.
First off, it stalls the network request waiting for a decision. As such, it does NOT allow a redirect to happen asynchronously - you have to decide right now, not in 5 seconds.
Second, it seems like you want the page to load, but in 5 seconds be redirected somewhere else - not keep "loading" for 5 seconds. Then webRequest is the wrong place to look.
What you want is a content script, a piece of JS code that will execute in the context of a tab after it loads.
I'll leave the manifest fields an exercise for the reader, and this code will work:
// Content script
setTimeout(function() {
window.location = "https://example.com/";
}, 5000);

Related

how to read cookies with browser extension

I want a browser extension to read the cookies of a webpage. I want also want the extension only to work on that particular webpage. So i have a button, load cookies and a background.js file:
chrome.extension.getBackgroundPage().console.log("loaded");
function getCookies(domain, name) {
chrome.extension.getBackgroundPage().console.log("loading cookeis");
chrome.cookies.getAll({ url: domain }, function (cookies) {
chrome.extension.getBackgroundPage().console.log(cookies);
});
// return await chrome.cookies.getAll();
}
getCookies(window.location.href, "csrftoken");
document.addEventListener("DOMContentLoaded", function () {
chrome.extension.getBackgroundPage().console.log("loading cookeis");
const loadCookies = document.getElementById("load_cookies");
// onClick's logic below:
loadCookies.addEventListener("click", function () {
getCookies(window.location.href, "x");
});
});
But it does seem like this does not get loaded.
I also get this, which lets me know that the worker is not loaded.
Manifest.json:
{
"manifest_version": 3,
"name": "Management Extension",
"short_name": "Management",
"version": "1",
"description": "A management tool ",
"permissions": ["cookies"],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "index.html"
}
}

Setting cookie with Chrome extension and Selenium Webdriver

I am trying to use a Chrome extension to set a cookie when I get a Selenium Webdriver instance to open a page. I have tried following a variety of ways suggested in different Stack Overflow posts but none of them ever show when I open the page inspector.
Manifest - I made sure to list permissions to any URL:
{
"name": "Test",
"description": "Test",
"version": "2.0",
"manifest_version": 2,
"permissions": ["cookies", "<all_urls>", "background", "tabs", "webRequest", "webRequestBlocking", "http://*/*"],
"background": {
"scripts": ["background.js"],
"persistent": true
} ,
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["script.js"]
}
]
}
Background JS - I have several attempts to create a cookie and none of them are showing when I inspect the web or background page:
chrome.cookies.set({ url: "https://google.com/", name: "CookieVar0", value: "123" });
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {test: testVar}, function(response) {
console.log("Response connected");
setCookie();
chrome.cookies.set({ url: "http://example.google.com", name: "CookieVar1", value: "123" });
});
});
},
...
function setCookie(){
console.log("Set Cookie");
chrome.cookies.set({"name":"Sample1","url":"http://developer.chrome.com/extensions/cookies.html","value":"Dummy Data"},function (cookie){
console.log(JSON.stringify(cookie));
console.log(chrome.extension.lastError);
console.log(chrome.runtime.lastError);
});
}
Content Script - I've read that you're normally not supposed to try to set cookies form the content script but some posts mentioned it so I tried it anyways:
window.addEventListener('load', loadEvent => {
console.log("Test 321");
// window.customlog = "Updated window!!!";
let window = loadEvent.currentTarget;
window.document.title='You changed me!';
chrome.cookies.set({ url: "http://example.google.com", name: "CookieVar3", value: "123" });
});
So its not a complete answer but something I realized was that no matter what URL you put in the cookie it is going to be filed under the url of the page you are running the extension. So chrome.cookies.set({ url: "https://google.com/", name: "CookieVar0", value: "123" }); was working but it wasn't under "https://google.com/" but "current page url" instead. The one setting "Sample1" was not working until I changed the format to match the one setting CookieVar0 and then it was fine.
So I still can't get it to work as desired everywhere but there is at least some progress. Hope this helps someone!

How to block some urls with chrome extension

I 'm trying to make my own chrome extension
to block the "seen" and "typing" status of facebook.
But it seems my way doesnt work
Can someone help me find my error?
manifest.json
{
"name": "Block Seen Typing",
"description": "Block Seen",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"webRequest",
"*://facebook.com/*",
"*://www.facebook.com/*",
"webRequestBlocking"
]
}
background.js
chrome.webRequest.onBeforeRequest.addListener(
{
urls: [
"https://www.facebook.com/ajax/messaging/typ.php", "https://www.facebook.com/ajax/mercury/mark_seen.php", "https://www.facebook.com/ajax/mercury/change_read_status.php" // here you put the URL that you want to block.
],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
},
["blocking"]);
Generaly i want to know how to block any webrequest that i want.
It looks like you forgot to actually include any code for a listener. Try something like this
chrome.webRequest.onBeforeRequest.addListener(function(d){
return {cancel:true};
},{urls:["https://www.facebook.com/ajax/messaging/typ.php",
"https://www.facebook.com/ajax/mercury/mark_seen.php",
"https://www.facebook.com/ajax/mercury/change_read_status.php"]},
["blocking"]);

Chrome webRequest event not firing on Chrome start

I am trying to make a Chrome extension to workaround Steam's annoying URL warning page. See this for example: https://steamcommunity.com/linkfilter/?url=http://67.69.104.76:84/marville/photos/planes/comet-162a.jpg
What I have so far works except when clicking a link would launch Chrome, in which case the Steam notice page is displayed.
Here is the page on webrequest: https://developer.chrome.com/extensions/webRequest
Any idea how I might get this to work at launch too?
background.js
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
var url = details.url;
var host = url.substring(43);
return { redirectUrl: host };
},
{
urls: ["*://steamcommunity.com/linkfilter/*"],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
},
["blocking"]
);
manifest.json
{
"manifest_version": 2,
"name": "Steam Link Filter Redirect",
"description": "Bypasses Steam link filtering.",
"version": "1.1",
"background": {"scripts":["background.js"]},
"permissions": [
"webRequest",
"*://steamcommunity.com/linkfilter/*",
"webRequestBlocking"
],
"icons": {
"16": "icon16.png",
"19": "icon19.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
The problem is, of course, that your code executes too late, after onBeforeRequest stage is done for the opening page. I don't think you can work around that.
You probably need to add a fallback mechanism. I suggest adding a content script that is injected in the linkfilter page and changes the page URL to the required one, for example:
"content_scripts": [ {
"matches": ["*://steamcommunity.com/linkfilter/*"],
"js": ["redirect.js"]
} ],
redirect.js:
location.replace(
decodeURIComponent( location.href.replace(/^.*?\?url=/, "") )
);
(I've made it more robust than .substring(43))

Chrome Extension - Context Menu On Specific Pages

I am wondering if it is possible to show the following context menu item only if it is on specific pages.
I think it has something to do with documentUrlPatterns (Which can be seen here as of typing this) but I am not sure how to implement it with the following code:
manifest.json
{
"name": "App Name",
"version": "1.0",
"manifest_version": 2,
"description": "Description",
"permissions": [
"contextMenus",
"tabs"
],
"background": {
"scripts": ["script.js"]
}
}
script.js
function getword(info,tab) {
chrome.tabs.create({
url: "http://www.google.com/search?q=" + info.selectionText,
})
}
chrome.contextMenus.create({
title: "Search: %s",
contexts:["selection"],
onclick: getword,
});
It would be great if you could provide a demo which will only work on specific sites of your choice (For instance, any directory of Stack Overflow and any directory of Google).
PS. The above code allows users to make a selection on any site and provides a button (In the context menu) which will search for what the user has selected on http://www.google.com/search?q= {Selection}
I have stripped down your code to demonstrate selective context menu option display.
manifest.json
{
"name": "zambrey",
"version": "1.0",
"manifest_version": 2,
"description": "Description",
"permissions": [
"contextMenus"
],
"background": {
"scripts": ["trial.js"]
}
}
trial.js
var showForPages = ["https://www.google.com/","*://github.com/zambrey/*","http://www.nytimes.com/"];
chrome.contextMenus.create({
"title": "zambrey",
"documentUrlPatterns":showForPages
});
Be sure to check out http://developer.chrome.com/extensions/match_patterns.html for more details on url pattern syntax.
Also refer to this http://developer.chrome.com/extensions/examples/api/contextMenus/basic.zip sample for more complex context menus.
I believe you want the "permissions" option in the manifest.json:
"permissions": [
"http://stackoverflow.com/*"
]
http://developer.chrome.com/extensions/declare_permissions.html

Categories

Resources