我正在学习如何创建Chrome扩展程序。我刚开始开发一个用于启动亚马逊网站并在其上执行搜索活动。我使用过内容脚本。但是我的代码在第一次警报后没有工作。请在下面找到我的代码:
<!-- language: lang-json -->
{
"name": "TestChrome Extension",
"version": "0.0.1",
"manifest_version": 2,
"background": {
"scripts": ["popup.js"]
},
"permissions": [
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [ "contentscript.js" ]
//"run_at": "document_end"
}
],
"browser_action": {
//"default_popup": "popup.html",
"default_icon": "icon.png",
"default_title": "That's the tool tip of extension"
}
}
<!-- language: lang-javascript -->
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function (tab) {
// Send a message to the active tab
alert("Clicked Recognised");
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var activeTab = tabs[0];
console.log("URL from main.js", activeTab);
chrome.tabs.sendMessage(activeTab.id, { "message": "clicked_browser_action" });
});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.message === "open_new_tab") {
chrome.tabs.create({ "url": request.url });
document.getElementById("twotabsearchtextbox").textContent = "Iphone 7";
document.getElementsByClassName("nav-input").addEventListener("click", function () {
window.alert("You Clicked Me");
});
}
}
);
chrome.tabs.executeScript(null, { file: "contentscript.js", allFrames: true });
<!-- language: lang-javascript -->
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.message === "clicked_browser_action") {
alert("CONTENT SCRIPT: I am running!");
// var firstHref = $("a[href^='http']").eq(0).attr("href");
var firstHref = "http://www.amazon.in";
//console.log(firstHref);
chrome.runtime.sendMessage({ "message": "open_new_tab", "url": firstHref });
}
}
);
我按照建议修改了我的脚本。请参阅上面的代码。