Chrome Extension - Background/Event JavaScript Not Responding or Loading - javascript

New to making extensions, I origally was attempting to load cookies but realised my EventPage.js didn't seem to be loading - since a basic console.log("Hello") wasn't loading.
I am loading the extension via Chrome "Load unpacked extensions", where manifest,content and background scripts are.
The code attached below is what I've been using to see if I can even get a console log from the event page. Only the content script loads, even If I press a key and that is logged.
CHROME:58
Any suggestions?
Manifest.SON
{
"manifest_version": 2,
"name": "Facebook Extension ",
"version": "1.0",
"description": "",
"permissions": ["storage", "webNavigation", "activeTab", "tabs", "cookies",
"*://*.facebook.com/*"],
"background": [
{
"scripts": ["event_Page.js"],
"persistent" : false
}
],
"content_scripts": [
{
"matches": ["*://*.youtube.com/*"],
"css": ["style.css"],
"js": ["jquery-2.1.0.min.js", "talkToEvent.js"]
}
]
talkToEvent.js
console.log("Hello World!s");
$(document).ready(function() {
console.log("DOM READY!");
$(document.documentElement).keydown(function (e) {
console.log("Key Has Been Pressed!");
chrome.runtime.sendMessage({Message: "getTextFile"}, function (response) {
;
})
})
});
event_Page.js
console.log("Atleast reached background.js")
chrome.runtime.onMessage.addListener (
function (request, sender, sendResponse) {
console.log("Reached Background.js");
if (request.Message == "getTextFile") {
console.log("Entered IF Block");
$.get("http://localhost:63342/Projects/StackOverflow/ChromeEXT/helloWorld1", function(response) {
console.log(response);
// to send back your response to the current tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {fileData: response}, function(response) {
;
});
});
})
}
else {
console.log("Did not receive the response!!!")
}
}
);

You have an incorrect manifest.json.
According event pages docs it should be an object, but in your manifest it is an array.
Correct manifest.json:
{
"manifest_version": 2,
"name": "Facebook Extension ",
"version": "1.0",
"description": "",
"permissions": [
"storage",
"webNavigation",
"activeTab",
"tabs",
"cookies",
"*://*.facebook.com/*"
],
"background": {
"scripts": [
"event_Page.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": [
"*://*.youtube.com/*"
],
"css": [
"style.css"
],
"js": [
"jquery-2.1.0.min.js",
"talkToEvent.js"
]
}
]
}
Also fixed missed comma and close bracket.

Related

chrome.runtime.sendMessage from webpage to chrome extension not return

My Chrome extension mv3 receives messages from webpage and replies to it. Here are the codes in webpage to send message to extension:
chrome.runtime.sendMessage(chromeExtensionId,
{
"Message": "Hello",
"Data":
{
"Name": 'Jason'
}
},
function(response) {
console.log("chrome.runtime.sendMessage", response);
});
and codes in extension's background.js to receive message and reply with true/false:
chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) {
console.log(message, sender));
sendResponse(true);
});
manifest.json:
{
"background": {
"service_worker": "background.js"
},
"action": {
"default_icon": {
"16": "images/logo16.png",
"32": "images/logo32.png"
},
"default_title": "My Extension"
},
"content_scripts": [ {
"all_frames": true,
"match_about_blank": true,
"js": [ "util.js", "contentscript.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_end"
} ],
"description": " ",
"externally_connectable": {
"matches": [ "https://*.mysite.com/*", "http://*.mysite.com/*" ]
},
"icons": {
"128": "/images/logo128.png",
"16": "/images/logo16.png",
"32": "/images/logo32.png",
"48": "/images/logo48.png"
},
"manifest_version": 3,
"name": "My Extension",
"permissions": ["cookies", "tabs", "proxy", "alarms", "storage", "downloads", "webRequest", "notifications", "nativeMessaging", "clipboardRead", "clipboardWrite", "declarativeNetRequest","declarativeNetRequestFeedback" ],
"host_permissions": ["<all_urls>"],
"version": "4.0.7"
}
Most of the time it works fine.
The only problem is when i set my webpage as startup page of chrome, which means the page is opened immediately when chrome starts, sendMessage does not return and console.log in both sender and receiver sides are not printed. There is no error output in console either. It looks like codes freeze inside sendMessage. What's going on there?
It's a known problem. Chrome intentionally delays extensions at browser startup to show the active tab faster. The workaround is to repeat sendMessage:
send('abcdefgkhgghfg........', {foo: 'bar'}, res => {
console.log('response', res);
});
function send(extensionId, msg, callback, retry = 20) {
const timer = setTimeout(send, 100, extensionId, msg, callback, retry - 1);
chrome.runtime.sendMessage(extensionId, msg, response => {
if (!chrome.runtime.lastError || !retry) {
clearTimeout(timer);
callback(response);
}
});
}

Storing items into a list from the values fetched by background script

I am new to extensions. my extension's purpose is to save the URLs of all tabs ever opened on the browser. This is my background script so far:
var URLs = [];
chrome.history.onVisited.addListener(storeURL);
chrome.storage.onChanged.addListener(function (changes, namespace) {
for (let [URL, { oldValue, newValue }] of Object.entries(changes)) {
URLs[URLs.length] = newValue;
}
});
function storeURL(HistoryItem) {
console.log("entered in storeURL function", HistoryItem)
chrome.storage.sync.set({ URL: HistoryItem?.url }, function () {
console.log('URL is set to ' + HistoryItem?.url);
});
}
The problem is that i am able to access the current url in developer tools but its not being stored in URLs.
Note: I want the extension to be autonomous and not popup. my manifest.json:
{
"name": "URL tracker",
"version": "0.0.1",
"manifest_version": 3,
"description": "Stores the browser URLs",
"action": {
"default_popup": "url.html",
"default_icon": "logo-small.png"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"css": [],
"js": ["content.js"]
}
],
"icons": {
"128": "logo-small.png",
"512": "logo-small-2.png"
},
"permissions": [
"history",
"tabs",
"activeTab",
"storage"
]
}

Chrome.tabs.sendMessage not working for no reason

I am making a chrome extension, and trying to send a message from the chrome extension page to the content.js. I know that in order to that I need to send the message to the bakcground.js and forward it to the content.js by sending it to either a specific tabs. I hvae done that many times and have not had any issues, but this time it just doesn't work.
main.js file (from the extension page):
chrome.runtime.sendMessage({
name: "stop"
})
background.js:
chrome.tabs.query({}, tabs => {
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].status == "complete") {
chrome.tabs.sendMessage(tabs[i].id, { msg: "Hello" })
}
}
})
content.js:
function recieve(msg) {
console.log(msg)
}
chrome.runtime.onMessage.addListener(recieve)
manifest.json:
{
"manifest_version": 2,
"name": "app",
"description": "app description",
"version": "3.0.0",
"icons": {
"19": "./images/icon_19.png",
"128": "./images/icon_128.png",
"150": "./images/icon_150.png"
},
"browser_action": {
"default_title": "title"
},
"permissions": [
"tabs",
"alarms",
"notifications"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"jquery-3.4.1.min.js",
"content.js"
]
}
],
"background": {
"scripts": [
"background.js"
]
}
}

Simulate clicking elements on the page from a Chrome extension?

I need to iterate and click all the elements with the class .star_gray on page, and keep the iteration and clicking going after redirection. Running JavaScript code cannot meet the second requirement, so I plan to write a Chrome Extension.
But I failed to simulate clicking events on web pages via the extension. My project is as below:
manifest.json
{
"manifest_version": 2,
"name": "Check'em All",
"description": "",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"persistent": true,
"scripts": ["jquery.js", "background.js"]
},
"content_scripts": [{
"matches": ["file:///*"],
"js" : ["popup.js"]
}],
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
]
}
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Check'em All!</title>
</head>
<body>
<h1>Check'em All!</h1>
<button id="check-btn">BUTTON</button>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('check-btn');
btn.addEventListener('click', injectScript);
});
function injectScript() {
alert('Handler called!');
chrome.tabs.executeScript(null, { file: 'background.js' });
}
background.js
$(document).ready(function(){
$('.star_gray').click();
$('a.btn.page_next').click();
});
With the code above, when I click the button(#check-btn) on the popup, nothing happens.
You can't get access DOM in background page. And per your code, you might need to learn more from Official Tutorial, since it seems you are confused with "popup", "background" and "content".
Assuming you want to trigger the click event for all elements with class ".star_gray" in the content page, the following code trigger those events once you click on browserAction.
manifest.json
{
"name": "Test",
"version": "1.0",
"permissions": [
"tabs"
],
"description": "Test",
"background": {
"persistent": false,
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"jquery.js",
"content.js"
],
"run_at": "document_end",
"all_frames": true
}
],
"browser_action": {
"title": "Test"
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {command: "click"}, function(response) {
console.log(response.result);
});
});
});
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
$('.star_gray').click();
$('a.btn.page_next').click();
sendResponse({result: "success"});
});
Improving the previous answer by #haibara-ai not to use the tabs permission.
Note that in your case you don't even need to watch for ready() since the script runs only when browser action is triggered which is presumably well after DOMContentLoaded.
manifest.json
{
"name": "Test",
"version": "1.0",
"permissions": [
"activeTab"
],
"description": "Test",
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"title": "Test"
},
"manifest_version": 2
}
background.js
var files = [
'jquery.js',
'content.js',
];
chrome.browserAction.onClicked.addListener(function() {
for (var file of files) {
chrome.tabs.executeScript({
file: file,
allFrames: true,
});
}
});
content.js
$('.star_gray').click();
$('a.btn.page_next').click();
Note, however that this only solves the 'simulate clicking events on web pages via the extension' question. It does not mean that 'keep the iteration and clicking going after redirection' will work. It's best you create another question with the details of what exactly you mean by that.

Manipulate DOM in chrome extension

I am trying to learn about chrome extensions but I am not able to understand how to manipulate DOM of a page using content_scripts.
manifest.json
{
"name": "First",
"version": "1.0",
"manifest_version": 2,
"description": "First extension",
"background": {
"scripts": ["test.js"]
},
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "jquery.min.js", "popup1.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"permissions" : [
"tabs",
"http://*/*"
]
}
test.js
function check(tab_id, data, tab){
if(tab.url.indexOf("google") > -1){
chrome.pageAction.show(tab_id);
}
};
chrome.tabs.onUpdated.addListener(check);
popup1.js
function myfunc(){
var x = $('#options option:selected').text();
$("body").append('Test');
alert(x);
//window.close();
}
$(document).ready(function(){
$('#options').change(myfunc);
});
The above code/extension works fine because myfunc gets called but it doesn't inject Test into the body of google.com.
So, where am I going wrong in accessing/manipulating the DOM.
If you want to play with browser tab DOM on event of popup. In this case you have to pass a message to content script from background script, or inject JavaScript into content script : have a look
manifest.json
{
"name": "First",
"version": "1.0",
"manifest_version": 2,
"description": "First extension",
"background": {
"scripts": ["test.js"]
},
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "jquery.min.js", "content_script.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"permissions" : [
"tabs",
"http://*/*"
]
}
content_script.js
function myfunc(){
var x = $('#options option:selected').text();
$("body").append('<div style="width:200px; height:200px; border: 1px solid red;"></div>');
}
$(document).ready(myfunc);
Now you will get A box with red border at the bottom of the page.
popup.js
function myfunc(){
var x = $('#options option:selected').text();
chrome.extension.sendMessage({sel_text: x});
}
$(document).ready(function(){
$('#options').change(myfunc);
});
test.js (used in background)
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
appendTextToBody(request.sel_text);
});
function appendTextToBody(text) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, {"code" : '$("body").append("Test : "'+text+');'}) ;
});
}
function check(tab_id, data, tab){
if(tab.url.indexOf("google") > -1){
chrome.pageAction.show(tab_id);
}
};
chrome.tabs.onUpdated.addListener(check);

Categories

Resources