I have a Chrome extension, and I'm trying to get it to add a Response Header to all pages.
Here's what I have in the manifest:
"permissions": [
"storage",
"clipboardRead",
"clipboardWrite",
"webRequest",
"webRequestBlocking",
"background"
],
"background": {
"scripts": ["background-script.js"]
},
Here's what I have in my background-script.js
chrome.webRequest.onHeadersReceived.addListener(function(details){
console.log('headers received');
details.responseHeaders.push({ name: 'X-XSS-Protection', value: '0' });
return { responseHeaders: details.responseHeaders };
}, {
urls: ['<all_urls>'],
types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
}, ['blocking', 'responseHeaders']);
I know that the background script executes, from putting a console.log in that file but outside the event listener, and observing it from the "Inspect views: background page" in the Extensions window.
However, I don't think the eventListener executes- I haven't seen that "headers received" message anywhere.
You have declared a truckload of unnecessary permissions in your manifest file, but not the most important ones: Host permissions. For example, if you want to intercept every http(s) request, add the "*://*/*" match pattern to the permissions section of your manifest.json:
"permissions": [
"webRequest",
"webRequestBlocking",
"*://*/*"
],
Related
I'm pretty new to chrome extension development, I'm trying to make a better PiP (Picture in Picture) that doesn't have the maximum window size limitation.
I'm using this extension as reference, it basically behaves the same way as the default PiP works with video.requestPictureInPicture() which is what I don't want to use because extension popup has limited window size.
Instead, I have a index.html page with my extension that is loaded with window.open in background.js, this index page will have a video element that the HTMLVideoElement is passed to.
I've tried using chrome.runtime.sendMessage to send the video to the video.js that the index.html page loads, but this doesn't seem to work with a HTMLVideoElement? I read elsewhere that I should do JSON.stringify/JSON.parse for this object but that results in undefined.
Relevant manifest.json:
"background": {
"service_worker": "background.js"
},
"content_scripts": [{
"all_frames": true,
"js": [ "content.js" ],
"matches": [ "*://*/*" ],
"run_at": "document_start"
}],
"web_accessible_resources": [{
"resources": [ "index.html" ],
"matches": [ "*://*/*" ]
}],
"manifest_version": 3,
"permissions": [ "storage", "scripting", "activeTab", "tabs" ],
content.js:
const videos = new Set();
window.addEventListener('canplay', e => {
if(e.target.tagName === 'VIDEO') {
videos.add(e.target);
chrome.runtime.sendMessage({
method: 'VIDEO_PLAYING'
});
}
}, true);
background.js:
await chrome.scripting.executeScript({
...
var win = window.open(chrome.runtime.getURL('index.html'), 'PiP');
win.focus();
chrome.runtime.sendMessage({
method: 'VIDEO',
data: JSON.stringify(video)
});
video.js: - this is the js that is just included on index.html
const onMessage = (request, sender) => {
if(request.method === 'VIDEO') {
var data = JSON.parse(request.data);
console.log(video.src); //undefined
}
};
chrome.runtime.onMessage.addListener(onMessage);
Maybe my method of going about doing this is entirely wrong. Are there other ways I can pass such objects to index.html like this?
Creating chrome extension which opens link in new tab and trying to click the button on newly opened tab -
I am able to open new tab using the extension but the content script is not executing on new tab.
Manifest File
{
"manifest_version": 2,
"name": " New Tab Launcher",
"description": "Create the tab and button click ",
"version": "1.0",
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [
{
"matches": [
"http://*/*", "https://*/*"
],
"js": [
"jquery-3.6.0.slim.min.js","contentScript.js"
],
"run_at": "document_end"
}
]
}
popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('addMeetingUrl');
checkPageButton.addEventListener('click', function() {
chrome.tabs.create({'url': "youtube.com"});
}, false);
}, false);
contentScript.js
alert("This is test");
$(document).load(function (e) {
alert("Testing content script" +$('#logo').text());
});
In above the first alert come successfully by next script does not launch.
I have tried Removing the $(document).load and adding $(document).ready both are not working for me.
#logo could be added to the DOM after the load and ready events are fired.
Check with the debugger if I've stated is true.
If so you will need to use MutationObserver.
Try removing "run at" as it will default to "document_idle" which is usually safer option
I'm working on migrating my Chrome extension into a Firefox addon. Honestly didn't think it would be that hard, but I've been trying to fix an issue of the background not wanting to send a message to the content script. (And yes, I've read everything online, but it just won't send the message inside an onUpdated listener)
EDIT
When I tried to put following line into the browserAction.onClicked listener it works, but it does not work in onUpdated?
browser.browserAction.onClicked.addListener(function(tab) {
browser.tabs.sendMessage(tab.id, {action: "isInstalled"});
});
END EDIT
And yes, the content script IS loaded, checked with an alert for the hostname.
Here's the code I used in the Chrome extension (background):
chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
chrome.tabs.sendMessage(tab.id, {
action: 'isInstalled'
});
});
Now here's what I have tried in Firefox addon (background):
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {greeting: "hello"});
});
Which is inside the browser.tabs.onUpdated listener as follows:
browser.tabs.onUpdated.addListener(function(tabId, changeInfo, tabInfo){
if(changeInfo.status === "complete"){
...
}
});
I also tried this, as I thought it would work: (yes tabId is correct).
browser.tabs.sendMessage(tabId, {action: "isInstalled"});
Now here's the onMessage listener on content script
browser.runtime.onMessage.addListener(function(request, sender) {
if(request.action == "isInstalled"){
alert("received");
var isInstalledNode = document.createElement('div');
isInstalledNode.id = 'extension-is-installed';
document.body.appendChild(isInstalledNode);
}
});
I keep getting the following error: "Error: Could not establish connection. Receiving end does not exist." which makes absolutely no sense for me.. Can anyone see the problem?
By the way, here's the manifest file:
{
"name": "Addon name",
"version": "1.3.0",
"manifest_version": 2,
"description": "...",
"icons": {
"48": "assets/images/icon_48_active.png",
"96": "assets/images/icon_96_active.png"
},
"browser_action": {
"default_title": "Name"
},
"background": {
"scripts":["background.js"]
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentscript.js"]
}
],
"permissions": [
"cookies", "tabs", "http://*/*", "https://*/*"
],
"web_accessible_resources": [
"modal.html", "assets/images/*"
]
}
chrome : 54.0.2840.87
This is my first chrome extension and I am new to javascript.
my manifest.json :
"background": {
"persistent": true,
"scripts": ["lib/jquery/jquery-3.1.1.min.js", "background.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content-scriptA.js",
"lib/jquery/jquery-3.1.1.min.js"],
"css": ["res/css/ms-0.0.1.css"]
}],
"content_security_policy": "script-src 'self' https://connect.facebook.net; object-src 'self'",
"permissions": [
"activeTab",
"tabs",
"storage",
"identity",
"<all_urls>"
],
background.js :
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (message_from_A) {
chrome.tabs.query({currentWindow: true, active: false}, function(tabs) {
chrome.tabs.executeScript(null, {file: "content-scriptB.js"});
});
}
if (message_from_B) {
chrome.tabs.query({currentWindow: true, active: false}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {to : "A", do: "..."});
});
});
and
chrome.runtime.onMessage.addListener(function(request, sender, response) {
console.log("...");
});
handlers for content-scriptA.js, content-scriptB.js each.
content-scriptA is for rendering A.html, content-scriptB is for rendering B.html in the same iframe while using my extension.
What I want do is when user wants to go back to A.html from B.html, render A.html with content-scriptA.js.
When I execute content-scriptB.js I thought both A.js and B.js are going, but when I sendMessage from background, none of them answered.
I tried to use port, reload same script and so on, but still can't find the way TT
Thanks for any help, and reading my question.
i can't figure out how to make it work. My script works by itself. but doesn't work with background.js. I want my google extension to work only if the user clicks on it's icon, so I have created the file background.js and putted the code:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "change_content.js"});
});
my manifest.json here:
{
"manifest_version": 2,
"name": "Name",
"description": "change content.",
"version": "3.0",
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["change_content.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"tabs", "http://*/*"
]
}
and here is the change_content.js:
var oldSource = document.documentElement.innerHTML;
document.body.innerHTML = changeContent(oldSource);
function changeContent(source){
.....
}
The reason you are having the issue where change_content.js is executing before you press the button is because thats how content scripts work. If you include a content script in your manifest.json it will load and execute that script. Try removing the "content_scripts" section from the manifest and you should see it work as it should.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "change_content.js"});
});
I've got a feeling the error lies in you using "null" as it might be searching for a tab with the tabId - null, you should try doing this instead?
chrome.tabs.executeScript({file: "change_content.js"});