在过去的 2 天里,我试图让在网页上看到的 HTML 通过 Chrome 扩展程序发送到特定的 API 端点(带 URL)。
主要问题是,并非所有在单击浏览器操作时在网页上看到的 HTML 内容都被发送。例如,如果网站是以稍后注入 HTML 的方式制作的,例如当用户在阅读页面 1 分钟后单击“显示更多马匹”时 - 这些新添加的马匹将不会被发送。
如果用户必须在浏览器操作后单击另一个按钮,我会很好。我认为我遇到的主要问题是我在加载内容后立即抓取 HTML。我一直试图改变这一点,但没有运气。在查看了各种 StackOverflow 帖子和 Chrome Ext 之后。docs 我有以下代码成功发送了 URL 和 HTML - 但不是所有的 HTML,如果它在 1 分钟后被添加说:
清单文件
{
"manifest_version": 2,
"name": "Horses extension",
"version": "0.3",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": true
}
],
"background": {
"scripts": ["background.js"]
},
"page_action": {
"default_title": "Horses extension",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs"
]
}
背景.js
// Called when the user clicks on the browser action.
chrome.runtime.onMessage.addListener(function (msg, sender) {
// First, validate the message's structure
if ((msg.from === 'content') && (msg.subject === 'showPageAction')) {
// Enable the page-action for the requesting tab
chrome.pageAction.show(sender.tab.id);
}
});
内容.js
// Inform the background page that
// this tab should have a page-action
chrome.runtime.sendMessage({
from: 'content',
subject: 'showPageAction'
});
// Listen for messages from the popup
chrome.runtime.onMessage.addListener(function (msg, sender, response) {
// First, validate the message's structure
if ((msg.from === 'popup') && (msg.subject === 'horsesInformation')) {
var a=[]
a.push(msg.url)
a.push(document.all[0].outerHTML)
response(a)
}
});
弹出窗口.js
window.addEventListener ("load", sendJobOpeningInfo, false);
function sendHorsesInformation(url_and_html) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 5000);
function checkForJS_Finish (){
clearInterval (jsInitChecktimer);
//GOAL: Post HTML and Domain to API
$.ajax({
url: "http://lvh.me:3000/api_url_xyz
type: "POST",
data: {url: url_and_html[0], html_source: url_and_html[1]},
success: function (data) {
var horsesTitle = document.getElementById('horses-title')
horsesTitle.append("Success!!")
}
});
}
}
// ...query for the active tab...
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
// ...and send a request for the Domain info...
chrome.tabs.sendMessage(
tabs[0].id,
{from: 'popup', subject: 'horsesInformation', url: tabs[0].url},
// ...also specifying a callback to be
//called from the receiving end (content script)
sendHorsesInformation);
});
弹出窗口.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<h3 id="horses-title"></h3>
</body>
</html>
为了将网页上看到的所有内容(即使在 JS 注入之后)发送到我的 API 端点,我需要更改什么?任何帮助将不胜感激!
好的,我知道了。只需将 checkForJS_Finish 函数与 ajax 函数从 content.js 中的 popup.js 移动,它就可以工作了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句