当用户点击扩展程序图标时,我正尝试在弹出窗口中获取当前标签页。
直到现在我已经尝试content-scripts
来设置popup.html中编写的标签的内部html。但它给了我一个不一致的行为。我也试过
chrome.browserAction.onClicked.addListener
但是当我们使用弹出窗口时它不起作用。
那么什么是捕获网址并在弹出窗口中显示它并在用户点击图标时让它工作的最佳方式?
这是我正在使用的manifest.json:
{
"name": "temp app",
"description" : "temp app",
"version": "1.0",
"manifest_version": 2,
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+F",
"mac": "MacCtrl+Shift+F"
},
"description": "Opens hello.html"
}
},
"browser_action" : {
"default_popup": "popup.html",
"default_icon": "hello_extensions.png",
"default_title": "default app"
},
"permissions" : [
"storage",
"contextMenus",
"tabs",
"<all_urls>"
],
"background" : {
"scripts" : ["background.js"],
"persistent" : false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content_script.js"]
}
]
}
我在popup.html中编写了以下代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js_src/script7.js"></script>
<script type="text/javascript" src="js_src/jquery-3.3.1.min.js"></script>
</head>
<body>
<div>
<span id="cu" class="cu">Default</span>
<button id="cub" class="cub" >Get URL</button>
</div>
</body>
</html>
script7.js的源代码:
document.getElementById('cub').onclick = function() {
// this method is not working while clicking the button
alert('Method called');
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
$('#cu').html(tabs[0].url);
});
}
window.onload = function() {
// window.onload giving problem when i clicking multiple time continuously on the icon
// also I doubt this is the best way to implement it
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
$('#cu').html(tabs[0].url);
});
}
答案 0 :(得分:0)
我在没有JQuery的情况下尝试了这样的代码,script7.js:
//wait for the DOM to be Loaded
window.addEventListener("DOMContentLoaded", function() {
function getCurrUrl(){
chrome.tabs.query({active: true, currentWindow: true}, function(arrayOfTabs) {
//the active tab y the only one of the arrayOfTabs at index = 0
var activeTab = arrayOfTabs[0];
var activeTabUrl = activeTab.url;
document.getElementById("cu").innerHTML = activeTabUrl;
})
}
document.getElementById("cub").addEventListener("click", getCurrUrl);
});
这对我有用,我希望它可以帮助你。