我是扩展程序开发的新手,因此我正在做一个扩展程序,该扩展程序从DOM
用户正在访问的页面获取产品的名称或价格。我做到了,但是我面临一个问题,我每次必须重新加载页面。
例如,如果用户在flipkart.com上说并访问某些产品,那么当我单击特定产品时(当然将要加载该产品的页面),我必须先单击扩展图标,然后再单击它获取我需要的数据。
如果页面已完全加载,然后单击扩展图标,则看不到所需的输出,而是在控制台上不打印任何内容。
换句话说,我该怎么做,而不必担心单击扩展程序图标和所需的数据,该操作会自动出现在我的popup.html
。
manifest.json
{
"manifest_version" : 2 ,
"name" : "myextension",
"version" : "1.0",
"browser_action":
{
"default_popup" : "popup.html"
},
"content_scripts": [
{
"matches": ["https://www.amazon.in/*","https://www.flipkart.com/*"],
"js": ["jquery-3.2.1.js","mycontentscript.js"]
}
],
"background" :{
"scripts" : ["background.js"]
},
"permissions": [
"*://flipkart.com/*","*://amazon.in/*", "tabs", "http://localhost/*", "webNavigation" //local host added
],
"content_security_policy": "script-src 'self' https://*/* default-src 'self' "
}
mycontentscript.js
var prdname=document.getElementsByClassName('_3eAQiD')[0].innerText; //just getting the name of prduct
myob ={
"prd" : prdname
};
var port = chrome.runtime.connect();
port.postMessage(myob); //sending product name to myscript.js
myscript.js
chrome.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(res){
alert(res.prd); ///just alerting here
});
});
你能帮我解决这个问题吗???
您可以运行一些代码以在后台脚本中保存产品页面。然后从您的弹出脚本中加载它(我假设myscript.js
是在哪里加载的)
因此此代码转到一直运行的后台脚本
//background.js
var productName
chrome.runtime.onMessage.addListener((request) => {
switch (request.command) {
case "saveProduct":
productName = request.productName
break
case "loadProcut":
return productName
break
}
})
以下是用户打开manifest.json中指定的页面时加载的内容脚本
// mycontentscript.js
var prdname=document.getElementsByClassName('_3eAQiD')[0].innerText
chrome.runtime.sendMessage({
command: "saveProduct"
productName: prdname
})
最后,这会从弹出式js加载产品名称
// myscript.js
chrome.runtime.sendMessage({
command: "loadProcut"
},function(productName){
console.log(productName)
alert(productName)
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句