这个问题似乎已经解决了,只要你注入(inject) javascript 的页面的 URL 以 www
开头。如果没有,你会怎么做?这是我的 list 的相关部分:
"content_scripts": [
{
"run_at": "document_start",
"matches": ["https://groups.google.com/forum/?fromgroups=#!newtopic/opencomments-site-discussions"],
"js": ["postMsg.js"]
}
],
根据另一篇 stackoverflow 帖子,问题是因为页面的 URL 不以“www”开头。这是否意味着您不能将 javascript 注入(inject) URL 不以“www”开头的安全页面,或者还有其他方法吗?这在过去从来都不是问题,因为我的扩展是使用版本 1 list 运行的。
忘记添加内容脚本:
var subject = document.getElementById("p-s-0");
subject.setAttribute("value", "foo");
ID 为“p-s-0”的元素是 Google 网上论坛帖子页面中的主题字段,因此该字段应显示为“foo”。
最佳答案
几个问题:
这是一个无效的 match pattern因为它们只指定了 URL 路径(
?
之前的部分)。将
匹配项
更改为:"matches": ["https://groups.google.com/forum/*"],
整体网址 (
https://groups.google.com/forum/?fromgroups=#!newtopic/opencomments-site-discussions
) 不实用,因为 Google 更改了网址参数随意。例如,fromgroups
并不经常出现,即使出现也可能没有=
。附加参数,如hl=en
来来去去。 (这就是为什么我之前的回答对我有用,但对你不起作用的原因。)因此,在 list 中使用
include_globs
将是一个困惑且容易出错的练习。
解决方案是检查内容脚本中的location.hash
。脚本设置为
"run_at": "document_start"
,因此内容脚本在 ID 为p-s-0
的任何节点之前运行。将 list 更改为
"run_at": "document_end"
。新的 Google 群组主要由 AJAX 驱动。因此,“新主题”页面通常是在没有实际加载整个新页面的情况下“加载”的。这意味着内容脚本不会重新运行。它需要监视“新的”AJAX 加载页面。
通过监控 the
hashchange
event 检查"new"页面.此外,
p-s-0
元素是由 AJAX 添加的,不会立即在"new"页面上可用。在setInterval
中检查此元素。
综合来看,
manifest.json 变为:
{
"manifest_version": 2,
"content_scripts": [ {
"run_at": "document_end",
"js": [ "postMsg.js" ],
"matches": [ "https://groups.google.com/forum/*" ]
} ],
"description": "Fills in subject when posting a new topic in select google groups",
"name": "Google groups, Topic-subject filler",
"version": "1"
}
内容脚本(postMsg.js) 变为:
fireOnNewTopic (); // Initial run on cold start or full reload.
window.addEventListener ("hashchange", fireOnNewTopic, false);
function fireOnNewTopic () {
/*-- For the pages we want, location.hash will contain values
like: "#!newtopic/{group title}"
*/
if (location.hash) {
var locHashParts = location.hash.split ('/');
if (locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
switch (locHashParts[1]) {
case 'opencomments-site-discussions':
subjectStr = 'Site discussion truth';
break;
case 'greasemonkey-users':
subjectStr = 'GM wisdom';
break;
default:
break;
}
if (subjectStr) {
runPayloadCode (subjectStr);
}
}
}
}
function runPayloadCode (subjectStr) {
var targetID = 'p-s-0'
var failsafeCount = 0;
var subjectInpTimer = setInterval ( function() {
var subject = document.getElementById (targetID);
if (subject) {
clearInterval (subjectInpTimer);
subject.setAttribute ("value", subjectStr);
}
else {
failsafeCount++;
//console.log ("failsafeCount: ", failsafeCount);
if (failsafeCount > 300) {
clearInterval (subjectInpTimer);
alert ('Node id ' + targetID + ' not found!');
}
}
},
200
);
}
关于javascript - 内容脚本未针对具有主题标签(且没有 www)的 URL 执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555833/