将当前网页的url显示为chrome扩展

Display the url of current web page into a chrome extension

本文关键字:显示 chrome 扩展 url 网页      更新时间:2023-09-26

我尝试在chrome扩展中显示当前网页的URL。我刚开始javascript和chrome扩展dev.

我的宣言.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://*/*"]
}

我的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>

我的contentscript.js

chrome.extension.sendRequest({
url: window.location.href
}, function(response) {
console.log(response.farewell);
);

我的背景.js

chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
    console.log(sender.tab ?
        "from a content script:" + sender.tab.url :
        "from the extension !!TEST!!");
}
);

我的弹出窗口和控制台中没有显示任何内容。。。

谢谢你的帮助向致以最良好的问候

chrome.extension.sendRequest已弃用。您应该使用chrome.runtime.sendMessage:

发件人

chrome.runtime.sendMessage({
  url: window.location.href
}, function(response) {
  console.log(response.farewell);
);

接收器

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if(request.url==="http://xxxxx.com"){
        chrome.runtime.sendMessage({farewell:"bingo"},function(response){});
    }
  }
);

顺便说一句,正如@Teepeemm所说,你不必两次加载内容脚本和背景js。contentscript.js将根据匹配模式注入到web上下文中。一旦扩展开始运行

,background.js就会被执行