2016-09-21 61 views
2

我有一个Chrome扩展,我想操纵GitHub上的一些DOM。当我刷新任何给定的页面时,所有工作都按预期工作,但如果我正常导航到该页面,则通常不会执行脚本。Chrome扩展只能在刷新时运行,而不能在页面导航上运行

manifest.json的

{ 
    "manifest_version": 2, 

    "name": "Name", 
    "description": "Detailed description", 
    "version": "1.3.5", 
    "content_scripts": [{ 
     "matches": ["https://github.com/*/*/issues/*"], 
     "js": ["jquery-2.1.0.min.js", "index.js"] 
    }], 
    "browser_action": { 
     "default_icon": "icon.png" 
    }, 
    "permissions": [ 
     "activeTab", 
     "https://ajax.googleapis.com/" 
    ] 
} 

index.js

$(document).ready(function() { 
    // DOM manipulating code 
    // removed for brevity 
}); 
+0

Github使用历史API的网站导航,你将不得不挂钩历史pushState函数,[如何通过history.pushState得到关于历史变化的通知?](http://stackoverflow.com/questions/4570093/how-to-get-notification-about-changes-of-the-history-via-history-pushstate) –

+0

@ZigMandel该帖子中的建议解决方案不适用于我的情况所以我开了一个新的问题。 – James

+0

@詹姆斯,如果你已经尝试了一些东西,但它不起作用,那么你应该在你的问题中提及它。不这样做只会浪费你要求帮助你的人的时间。 – Makyen

回答

1

当你从另一个导航到GitHub的页面,在该页面的容器被更新,而不是整个页面。

因此,从我的经验来看......如果您从回购的主页开始并切换到问题页面,则扩展并不总是注意到这一变化。因此,我建议改变清单matches所有github上的,而不是仅仅的问题:

{ 
    "manifest_version": 2, 
    "name": "Name", 
    "description": "Detailed description", 
    "version": "1.3.5", 
    "content_scripts": [{ 
     "matches": ["https://github.com/*"], 
     "js": ["jquery-2.1.0.min.js", "index.js"] 
    }], 
    "browser_action": { 
     "default_icon": "icon.png" 
    }, 
    "permissions": [ 
     "activeTab", 
     "https://ajax.googleapis.com/" 
    ] 
} 

如果不工作,那么你的代码中,监测一个“pjax:结束”的文档事件:

document.addEventListener("pjax:end", function() { 
    // run code/call function 
}); 
+0

什么时候发生“pjax:end”事件?我试着实现你的两个建议,问题仍然存在 – James

+0

这个解决方案应该可以工作,我使用同样的方法。 @詹姆斯,确保你已经重新加载了整个扩展和站点(用pjax:end重新输入新的内容脚本)。 – wOxxOm

+0

GitHub完成将新内容加载到目标容器后触发“pjax:end”。 – Mottie