Basic Google Chrome Extension Noob Question - google-chrome-extension

I am trying to create a basic Google Chrome Extension that simply copies the source HTML code on the page I am on. I have never created a Chrome extension and I am really stuck and would appreciate some help. I started the extension using the Chrome guide and from what I have read on the internet is I content scripts to access the webpage. I don't know how to call the content scripts however. I tried using import statements but I received errors - I think I am really misunderstanding how the whole thing works. I am trying to also get the console log to display in the webpage console, instead of the chrome extension console.
popup.html
<!DOCTYPE html>
<html>
<head>
<style>
button {
height: 30px;
width: 30px;
outline: none;
}
</style>
</head>
<body>
<button id="changeColor"></button>
<script src="popup.js"></script>
</body>
</html>
manifest.json
"name": "Company Websites",
"version": "1.0",
"description": "Build an Extension!",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"page_action": {
"default_popup": "popup.html"
},
"permissions": ["storage","declarativeContent"],
"manifest_version": 2
}
content.js
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("changeColor").addEventListener("click", handler);
});
// The handler also must go in a .js file
function handler() {
console.log("hello?");
//somehow copy source code
}
background.js
chrome.runtime.onInstalled.addListener(function() {
chrome.storage.sync.set({color: '#3aa757'}, function() {
console.log("The color is green.");
});
});
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: {hostEquals: '* insert target web address*'},
})
],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
Any help would be appreciated!

Make another file called load.js and do an XML HttpRequest, then include it in the popup.html.
popup.html
<script src="load.js"></script>
load.js
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = xhttp.responseText;
}}
xhttp.open("GET", "website url", true);
xhttp.send();
}
loadDoc()
From there you can store and retrieve it in local storage, console.log(data), or use it in document.getElementById('ID').innerHTML = data

Related

How to modify html element on page load in Chrome extension

I have a button element on the popup.html file that I want to modify on page load via the content.js file. However, when I tried the below code it did not work (text button text does not change).
How do I change the button text when the content loaded?
popup.html:
<html>
<body>
<button id="to-modify-button">no text</button>
<script src="popup.js"></script>
</body>
</html>
popup.js:
const btn = document.getElementById("to-modify-button");
chrome.runtime.onMessage.addListener(function (
request,
sender,
sendResponse
) {
if (request.theme === "dark") {
btn.textContent = "Disable dark mode";
} else {
btn.textContent = "Enable dark mode";
}
});
content.js:
(() => {
chrome.runtime.sendMessage({ theme: "dark" });
})();
You can't push to popup. pull from popup.
manifest.json
{
"name": "content_scripts + popup",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"js": [
"content.js"
],
"matches": [
"<all_urls>"
]
}
],
"action": {
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<button id="to-modify-button">no text</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
const btn = document.getElementById("to-modify-button");
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, "message", (response) => {
console.log(response);
if (response.theme === "dark") {
btn.textContent = "Disable dark mode";
} else {
btn.textContent = "Enable dark mode";
}
});
});
content.js
console.log("content.js");
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message);
sendResponse({ theme: "dark" });
return true;
});

How can I get the URL and Title of current TAB in my chrome browser and show it when the users clicks on my extension icon

I am building an extension, I want my extension to work as follows :
When ever the user visits any website my extension should fetch the url and title of that website and display it whenever the user clicks on the extension icon
this is my code
(manifest.json)
{
"manifest_version": 2,
"name": "My Launcher",
"description": "Quick launch lol Media",
"version": "1.0.0",
"icons": { "128": "icon_128.png" },
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["activeTab"],
"background": {
"scripts": ["popup.js"],
"persistent": false
}
}
(popup.html)
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="popup.js">
</script>
<script src="jquery-3.3.1.min">
</script>
</head>
<body>
<h2 id="greet">Hello world!!!</h2>
</body>
</html>
(popup.js)
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
tabs[0].url; //url
tabs[0].title; //title
$('#greet').text((tab[0].url).val());
});
});
When the user clicks on the extension icon he should see a message displaying the url and title of the current webpage he/she is visiting.
In your content script include the following in a function and then call it to return the tab URL...
function return_tab_url(){
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
var tabURL = tabs[0].url;
//returns https://...
return tabURL;
});
}
Put a breakpoint at tabURL in devtools to observe the result or use alert to debug. Hope this helps.

How to access the original page from the Chrome extension JS file

I'm trying to figure out how to access in my js file the original page from the extension page.
Lets say I'm in example.com/test.html, I want to know how do I access test.html from my extension (the download.js which is been called from download.html)
Edit: So I've added another js script in the middle however I never reach the download.js
Update Thanks to wOxxOm I've manage to get what I wanted, I've updated the question for follow searches.
Here is my code:
background.js
chrome.tabs.executeScript(null, { file: "jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "download.js" }, function(results){
JSON.stringify(results);
var i;
for (i = 0; i < results[0].length; ++i) {
chrome.downloads.download({
url: results[0][i],
filename: "/Users/testusr/Documents/"
});
}
});
});
download.js
[].map.call(document.querySelectorAll('[data-bimg] img'), function(e) {
return e.src;
});
manifest.json
{
"manifest_version": 2,
"name": "test",
"version": "1.0",
"description": "This extension will download all product images",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "download.html"
},
"permissions": [
"activeTab",
"downloads"
]
}
download.html
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="background.js"></script>
</head>
<body>
<h1>Test</h1>
</body>
</html>

Chrome Extension Content script cannot listen an event until page is refreshed

I would like to create an extension to inject html into every page opened as soon as it is installed without reloading.
webpage.html:
<html>
<head>
<meta charset="utf-8" />
<title>Extension</title>
<script>
var go = function() {
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
};
</script>
</head>
<body>
Click me
</body>
</html>
manifest.json:
{
"name": "Chrome Extension Test",
"version": "0.1",
"description": "Test",
"manifest_version": 2,
"background" : {
"persistent": true,
"scripts": ["background.js"]
},
"permissions": ["http://*/*", "https://*/*"],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"]
}]
}
content_script.js:
(function() {
document.addEventListener("hello", function(data) {
chrome.runtime.sendMessage("test");
});
})();
background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
alert("message received");
console.log("background message received");
});
If the extension is already installed, it works. But if the extension is installed after loading web page, the content script can't receive an event dispatched from the web page unless reload.
Is there a way to receive the event in content script without reloading?
There is a long canonical answer here.
In short, if you need your content script on initialization, you should do a chrome.tabs.query({}, ...); at the background script initialization, that would inject scripts in all tabs with chrome.tabs.executeScript({file: "content_script.js"});.

Chrome Extension sendMessage error from content script to background html

I just updated my chrome extension to json version 2, and am trying to get my extension to work again. The problem is sendRequest was depreciated along the way. So I copy the code from https://developer.chrome.com/extensions/messaging.html into my script and modify it to my own variable names, and it doesn't work.
So then I go back and put in the original code and it still doesn't work. I have read multiple questions that are similar [and hopefully this won't get closed as a duplicate, because none of them were the same as my situation].
manifest.json:
{
"background": {
"page": "background.html"
},
... ... ...
"content_scripts": [ {
"css": [ "style.css" ],
"js": [ "jq.js", "script.js" ],
"matches": [ "http://*.craigslist.org/*/*.htm*" ]
} ],
... ... ...
"permissions": [ "tabs", "http://*.craigslist.org/*/*.htm*" ],
"manifest_version": 2,
"update_url": "http://clients2.google.com/service/update2/crx",
"version": "3.0"
}
background.html:
<html>
<script type='text/javascript'>
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
});
</script>
</html>
script.js:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
Now I run a page [on craigslist], and go to the Console and this is the error:
Port error: Could not establish connection. Receiving end does not exist.
TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://dhmjefbokfkjpdbigkadjpgjeflchgea/script.js:9:23
I use Chrome Beta on Ubuntu 12.10 64-bit (Google Chrome: 27.0.1453.15 (Official Build 191758) beta)
You are sending messages from both your background and your content script, but not trying to receive them at all. Try listening for messages in one or both of those places. Also, inline code is against the CSP so move it all to an external file.
For example:
manifest.json
"background": {
"scripts": ["background.js"]
},
background.js
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
sendResponse({farewell:"goodbye"});
});
script.js
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
Also, chrome.tabs.getSelected() has been deprecated as well, so use chrome.tabs.query() instead.
background script
chrome.tabs.getAllInWindow(null, function(tabs) {
$.each(tabs, function() {
chrome.tabs.sendRequest(this.id, {"action":"action_name"} );
});
});
content script
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
if(request.action === 'action_name')
{
alert('handle event in the content script!!!!')
}
});

Resources