Reputation: 21
I try to display the URL of the current web page in a chrome extension. I just begin javascript and chrome extension dev.
My manifest.json
{
"manifest_version": 2,
"version": "0.1",
"name": "!!!",
"author": "!!!",
"description": "Extension !!!",
"icons": {
"default_icon": "logo2.png"
},
"browser_action": {
"default_icon": "logo2.png",
"default_popup": "popup.html"
},
"options_page": "options.html",
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentscript.js"]
}],
"web_accessible_resources": ["contentscript.js"],
"permissions": ["tabs", "http://*/*", "https://*/*"]
}
My popup.html:
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Extension !!!!!!!!!</title>
<link rel="stylesheet" href="stylesheet.css">
<!--<script type="text/javascript" src="tracker.js"> </script>
<script src="canvas.js"></script>-->
<script src="background.js"></script>
<script src="contentscript.js"></script>
</head>
<body>
<!--=========TITLE============== -->
<div id="main-logo">
<div id="logo"><img src="logo2.png"><img></div>
<h1>!!!!</h1>
</div>
<div id="main">
<!--=============Display URL===========-->
<div id="main-url">
<script src="background.js"></script>
</div>
</div>
My contentscript.js
chrome.extension.sendRequest({
url: window.location.href
}, function(response) {
console.log(response.farewell);
);
My background.js
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension !!TEST!!");
}
);
Nothing diplay in my popup and in the console...
Thanks for your help Best regards
Upvotes: 1
Views: 1691
Reputation: 5727
chrome.extension.sendRequest is deprecated. You should use chrome.runtime.sendMessage:
Sender
chrome.runtime.sendMessage({
url: window.location.href
}, function(response) {
console.log(response.farewell);
);
Receiver
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.url==="http://xxxxx.com"){
chrome.runtime.sendMessage({farewell:"bingo"},function(response){});
}
}
);
BTW, as @Teepeemm said, you don't have to load content script and background js twice. contentscript.js will be injected into web context according to the matches pattern. And background.js will be executed once the extension start running
Upvotes: 1