我正在开发一个 chrome 扩展程序,每次用户在浏览器中加载新网址时,该扩展程序都会进行 ajax 调用。当 ajax 调用的结果传入时,我想使用 ajax 调用的结果对 DOM 进行更改。我对 chrome 扩展开发还很陌生,但从我读到的内容来看,最好在后台脚本中进行 ajax 调用,然后将结果发送到可以修改 DOM 的内容脚本。
我能够进行ajax调用并在background.js中获取结果,但是当我尝试将其发送到popup.js时,我没有收到我需要的数据警报,因此我可以修改DOM。
我有:
background.js
chrome.webRequest.onBeforeRequest.addListener(
process,
{urls: ["*://www.example.com/*"]},
);
function process(details){
var xhr;
xhr = new XMLHttpRequest();
xhr.open("GET", "https://example2.com/", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
return myCallback(xhr.responseText);
}
};
xhr.send();
chrome.webRequest.onBeforeRequest.removeListener(getDeals);
return
}
function myCallback(resp){
chrome.runtime.sendMessage({
data: resp
});
}
popup.js
chrome.runtime.onMessage.addListener(
function(data) {
alert(data);
}
);
manifest.json
{
"manifest_version": 2,
"name": "My program",
"description": "my description",
"version": "1.0",
"icons": {"16": "daisy_16.png",
"48": "daisy_48.png",
"128": "daisy_128.png"},
"permissions": [
"background", "webRequest","webRequestBlocking", "webNavigation", "tabs", "https://example2.com/*", "declarativeContent", "storage", "<all_urls>"
],
"externally_connectable": {
"matches": ["*://*.example2.com/*"]
},
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["jquery-3.4.1.min.js", "popup.js"],
"run_at": "document_end"
}]
}
最佳答案
要向选项卡发送消息,您需要 chrome.tabs.sendMessage带有 tabId
和 frameId
,所以让我们将 details
传递给 myCallback 并在内部使用它:
chrome.webRequest.onBeforeRequest.addListener(
process,
{urls: ['*://www.example.com/*']},
);
function process(details) {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example2.com/');
xhr.onload = () => myCallback(xhr.responseText, details);
xhr.send();
}
function myCallback(data, {tabId, frameId}) {
chrome.tabs.sendMessage(tabId, {data}, {frameId});
}
此代码假设您在每个 iframe 中运行内容脚本,而不仅仅是在主页中:
"content_scripts": [{
...........
"all_frames": "true"
}]
否则使用0
仅发送到主页的内容脚本:
function myCallback(data, {tabId}) {
chrome.tabs.sendMessage(tabId, {data}, {frameId: 0});
}
关于javascript - 如何在每个页面请求时发送 ajax 调用,并使用 ajax 调用的结果对 DOM 进行更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419303/