我需要从 GWT 应用程序中使用 Disqus,因此我需要解决应用程序中的虚拟页面更改时按需加载线程的问题。
少量的逆向工程和实验使我构建了一个实用程序类(如下)。
主要见解是:
- 有一个未记录的全局参数
disqus_container_id
,它允许您将评论放在您喜欢的任何地方。如果这在将来的某个版本中不起作用,我的后备方案是临时将目标元素的 id 设置为disqus_thread
,添加注释,然后将其更改回原始 id。
- 由于这是使用 JSNI 为 GWT 开发的,因此我需要在原始窗口上下文中设置全局参数,可以通过
$wnd
. 我相应地更改了默认的 Disqus 嵌入代码。之前我没有意识到所有全局变量都在 Window 对象中,但是我学到了一些新东西。
- 您可以重复使用同一个容器,Disqus 似乎在您激活它时会清除内容。
- 这会在 DOM 中留下大量 script 标签的副本。也许在它们被使用后清理它们也是一个好主意。
DISQUS.reset
或者,我可能会使用其他答案中描述的方法进行更多实验。
只为单独使用 JS 的人提取关键信息,这应该允许您将 Disqus 线程粘贴到您喜欢的任何地方:
function loadComments(container_id, shortname, identifier, developer) {
// CONFIGURATION VARIABLES
window.disqus_container_id = container_id;
window.disqus_developer = developer ? 1 : 0;
window.disqus_shortname = shortname; // required
if (identifier) window.disqus_identifier = identifier;
// DON'T EDIT BELOW THIS LINE
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
这是完整的 GWT 实用程序类。到目前为止,我只实现了我需要的参数。
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Widget;
public class Disqus {
public static boolean developer = false;
public static String shortname;
public static void showComments(Widget where, String identifier) {
showComments(where.getElement(), identifier);
}
public static void showComments(Element where, String identifier) {
if (shortname == null)
throw new IllegalArgumentException(
"You must specify the disqus shortname before displaying comments");
// Store the original id of the target element
String id = where.getId();
if (id == null) {
id = "disqus-" + Integer.toHexString(Random.nextInt());
where.setId(id);
}
// Update the id temporarily
where.setId("disqus_thread");
// Load the comments
loadComments(id, shortname, identifier, developer);
}
private static native void loadComments(String container_id, String shortname, String identifier, boolean developer) /*-{
// CONFIGURATION VARIABLES
$wnd.disqus_container_id = container_id;
$wnd.disqus_developer = developer ? 1 : 0;
$wnd.disqus_shortname = shortname; // required
if (identifier) $wnd.disqus_identifier = identifier;
// TODO
// disqus_url
// disqus_title
// disqus_category_id
// DON'T EDIT BELOW THIS LINE (sorry, I've edited it anyway)
(function() {
var dsq = $doc.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + shortname + '.disqus.com/embed.js';
($doc.getElementsByTagName('head')[0] || $doc.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}-*/;
}