Chrome Extension : Access DOM after chrome.tabs.update - google-chrome

My aim is to search for a div by id if it exists in all languages my site supports.
manifest.json
{
"manifest_version": 2,
"name": "Hello World!",
"description": "This extension is to check if link is not visible when it should not :)",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [ {
"js": [ "jquery-1.11.1.min.js"],
"matches": [ "http://*/*", "https://*/*"]
}],
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
]
}
popup.html -
<html>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<style>
table{background:#CCC;border:1px solid #000;}
table td{padding:15px;border:1px solid #DDD;}
</style>
<body>
<input type="hidden" id="currentLink"/>
<hr />
Checking ...
<div id="dynamictable"></div>
<script type="text/javascript" src="currentUrl.js"></script>
</body>
</html>
currentUrl.js -
chrome.tabs.getSelected(null, function(tab) {
var currentTab = (tab.url);
var languages = [ "en", "fr" ];
$('#dynamictable').append('<table></table>');
var table = $('#dynamictable').children();
var i;
for (i = 0; i < locales.length; ++i) {
chrome.tabs.update(tab.id, {active:true, url: currentTab + "?languageParam=" + languages[i]});
var query = document.querySelector("div#header");
if (query) {
alert("This page has a friendly div");
}
table.append("<tr><td>" + languages[i] + "</td><td>" + "</td></tr>");
}
});
In above query is not coming. How can I parse the DOM after chrome.tabs.update ?

Have you tried using a callback?
The api defines the function as chrome.tabs.update(integer tabId, object updateProperties, function callback).
Perhaps you could change
chrome.tabs.update(tab.id, {active:true, url: currentTab + "?languageParam=" + languages[i]});
for
chrome.tabs.update(
tab.id,
{active:true, url: currentTab + "?languageParam=" + languages[i]},
function() { // this is the callback you may want to use.
var query = document.querySelector("div#header");
if (query) {
alert("This page has a friendly div");
}
}
);
This may not work as-is, but I hope the idea is clear.

Related

what does this error message on my chrome extension, from popup.html mean and how to fix it?

So as you already read in the title my problem hast todo with popup.html
I have no idea what the problem is please help me!
this is the error code
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
Stacktrace
popup.html:0 (Anonyme Funktion)
popup.html is:
<!DOCTYPE html>
<html>
<head>
<style>
#popup-container {
width: 600px;
height: 800px;
}
</style>
<title>DissBott</title>
</head>
<body>
<h1>ChatGPT Extension</h1>
<p>input</p>
<textarea id="input"></textarea>
<br>
<button id="submitButton">Submit</button>
<button id="clearButton">Clear</button>
<br>
<p>Response:</p>
<p id="response"></p>
<script src="popup.js"></script>
</body>
</html>
popup.js is:
// Popup Script
//background.js
const submitButton = document.getElementById("submitButton");
const clearButton = document.getElementById("clearButton");
const promptTextarea = document.getElementById("prompt");
const responseParagraph = document.getElementById("response");
submitButton.addEventListener("click", function() {
// onClick's logic below:
// Get the prompt from the textarea
const prompt = input;
// Send the message to the background script
chrome.runtime.sendMessage({
message: "clicked_browser_action",
prompt: prompt
}, function(response) {
// Display the response
responseParagraph.innerText = response;
});
});
clearButton.addEventListener("click", function() {
// Clear the textarea
promptTextarea.value = "";
// Clear the response
responseParagraph.innerText = "";
});
my manifest.json
{
"manifest_version": 3,
"name": "DissBot",
"description": "This is an extension that uses the ChatGPT model.",
"version": "1.0",
"host_permissions": [
"https://api.openai.com/"
],
"action": {
"default_popup": "popup.html"
},
"background": {
"script": ["bg.js"]
}
}
I tried to make a chrome extension it didnt work.
Here is a sample of chrome.runtime.sendMessage.
manifest.json
{
"name": "hoge",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html"
}
}
popup.html
<html>
<body>
<button id="send">Send</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
document.getElementById("send").onclick = () => {
chrome.runtime.sendMessage("send", (respose) => {
console.log(respose);
});
}
background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message);
sendResponse("response");
return true;
});

Cannot read property 'onBoundsChanged' of undefined

When I write a extension for google chrome I got error as title question. Below is my code:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, {
file: "libs/jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "src/content.js"
});
});
});
chrome.app.window.onBoundsChanged.addListener(function (tab) {
chrome.tabs.executeScript(null, {
file: "libs/jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "src/content.js"
});
});
});
Firstly, I got success with onClicked event. But I want extension work when I resized window. But when I add 2nd event. Error occur
Please help me this error
Thank you
manifest.json
{
"name": "Bootstrap Grid for any Website",
"version": "1.1.0",
"manifest_version": 2,
"description": "Quickly toggle a Bootstrap Grid for any website. Easy to use, easy success.",
"browser_action": {
"default_icon": "src/icon48.png"
},
"background" : {
"scripts" : [
"src/background.js"
]
},
"content_scripts": [
{
"js": [ "src/send_value.js" ],
"matches": [ "<all_urls>" ],
"all_frames": true,
"run_at": "document_end"
}
],
"permissions": ["activeTab"]
}
I think you've mixed up chrome extensions and chrome apps. As we can read here, chrome.app.window is
not associated with any Chrome browser windows
I recommend you create content.js script where you put something like this:
window.addEventListener('resize', function(e){
....
// here you send message to background.js
var message = { info: "window resized");
chrome.runtime.sendMessage( "", message );
})
content.js must be executed in every tab you specified in manifest file.
In your background.js you should write:
chrome.runtime.onMessage.addListener(function(message){
if(message.info === "window resized"){
chrome.tabs.executeScript(null, // ..... the stuff you've written above
......
}
});
Links:
chrome.runtime.sendMessage
chrome.runtime.onMessage
Good luck!
UPD (in manifest file):
"background": {
"scripts": [ "background.js"]
},
"content_scripts": [
{
"js": [ "content.js" ],
"matches": [ "<all_urls>" ],
"all_frames": true,
"run_at": "document_end"
}
],
UPD 2. This snippet is from my working extension manifest:
"web_accessible_resources": [
"main.js",
"style.css",
"options/options.css",
"options/options.js"
]
Your extension folder look like:
Your manifest.json file:
{
"name": "Bootstrap Grid for any Website",
"version": "1.1.0",
"manifest_version": 2,
"description": "Quickly toggle a Bootstrap Grid for any website. Easy to use, easy success.",
"browser_action": {
"default_icon": "src/icon48.png"
},
"background" : {
"scripts" : [
"background.js"
]
},
"permissions": [
"tabs",
"<all_urls>"
],
"web_accessible_resources":[
"src/content",
"src/content_temp",
"libs/jquery.js"
]
}
background.js:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, {
file: "libs/jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "src/content.js"
});
});
});
chrome.runtime.onMessage.addListener(function(message){
if(message.info !== 1) return;
chrome.tabs.executeScript(null, {
file: "src/content_temp.js"
});
});
And your send_value.js file I put into content.js:
window.addEventListener('resize', function (e) {
// here you send message to background.js
var message = {info: 1}
chrome.runtime.sendMessage("", message);
});
function devTool() {
As for me, it works fine! :-)

Getting data from user page in chrome extension

I am creating a chrome extension which extracts the inner text of h2> from the page in which the user is browsing. Although I learned about content scripts and have used it but it is not working I don't know where is the problem. If anyone could help me that would be greatly appreciated.
This is the js code:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('button');
link.addEventListener('click', function() {
updateresult();
});
});
function updateresult() {
var i;
var x =document.getElementsByTagName("h2");
for(i=0; i< x.length ; i++)
{
document.getElementById("result").innerHTML = (x[i].innerHTML + "\n");
}}
This is the manifest file which I am using:
{
"manifest_version": 2,
"name": "Header Extractor",
"description": "Extension to search header",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"16": "icon.png",
"48": "icon.png",
"128": "icon.png",
"default_popup":"popup.html",
"default_title": "Open And Search headers"
},
"permissions": [
"storage",
"activeTab" ,"tabs"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [ "popup.js"],
"run_at": "document_end"
}
]
}
Have you already created a result div to paste your results in?
Also your current function only returns one h2 value. Let's use concat to output them all together.
function updateresult() {
var i;
var x = document.getElementsByTagName("h2");
var string = "";
for(i=0; i<x.length; i++)
{
string.concat(x[i].innerText + "\n");
}
document.getElementById("result").innerText = string;
}
As a side note, we use innerText instead.

How to run a extension in the windows and tabs that will be open

I have an extension to count the number of stylesheets.
When the icon is pressed, the stylesheets of all opened windows or tabs are shown.
However, the extension has no effect on the windows and tabs that are opened later.
How can I solve it ?
manifest.json
{
"name": "StyleSheets counter",
"description": "It counts the stylesheets linked with the web page",
"version": "2.0",
"permissions": [
"tabs",
"*://*/*",
"activeTab",
"debugger"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "SS Counter"
},
"icons": {
"48": "on.png",
"48": "off.png"
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
executeScriptsInExistingTabs();
});
function executeScriptsInExistingTabs(){
chrome.windows.getAll(null, function(wins) {
for (var j = 0; j < wins.length; ++j) {
chrome.tabs.getAllInWindow(wins[j].id, function(tabs) {
for (var i = 0; i < tabs.length; ++i) {
if (tabs[i].url.indexOf("chrome://") != 0) {
chrome.tabs.executeScript(tabs[i].id, { file: 'counter_ss.js' });
}
}
});
}
});
}
counter_ss.js
var theSheets = document.styleSheets;
alert("Number of stylesheets: " + theSheets.length);
Add onClicked event listener with your function executeScriptsInExistingTabs as callback.
I have already the solution, for the new tabs and for the ones whose URL is changed:
chrome.tabs.onCreated.addListener(function(tab) {
//none is done here
});
chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
if (info.status == "complete") {
chrome.tabs.executeScript(tabid, {file:'counter_ss.js'});
}
});
The code inside
chrome.tabs.onUpdated.addListener
is run both, when the new tabs are open and when the URL of a tab is changed. So to avoid duplication, none is done in the
chrome.tabs.onCreated.addListener
However, it must be there (altough empty).

chrome.webRequest not working on Chrome 17

I have problems in chrome-extension API (chrome.webrequest).
My manifest.json
{
"name": "tesst",
"version": "1.0",
"description": "test",
"permissions": ["webRequest","webRequestBlocking",
"http://*" ],
"options_page": "options.html",
"background_page": "background.html"
}
My background.html
<script>
chrome.webRequest.onBeforeSendHeaders.addListener( function(info) { loldogs = [{name:'x', value: 'xx'}]; console.log("URL: " + info.url); info.requestHeaders.push.apply(info.requestHeaders,loldogs); for(var i in info.requestHeaders) { for (var key in info.requestHeaders[i]){ console.log("header "+i+" ["+key+"] "+info.requestHeaders[i][key]); } }
return {requestHeaders: info.requestHeaders}; }, {urls: ["<all_urls>"]}, ["blocking", "requestHeaders"]);
</script>
When I connect to some url (ex: http://google.com), chrome not set header {name:'x', value: 'xx'} in http-request. And it does not log anythings in console.
Change "http://*" to "http://*/*" in permissions.