jQuery.ready未从Greasemonkey脚本中调用
jQuery .ready not getting called from within Greasemonkey script
我正试图编写一个简单的Greasemonkey脚本,但作为Javascript的初学者和Greasemonky的新手,我不断遇到问题。到目前为止,这是我的代码:
// ==UserScript==
// @name TEDToYoutube
// @include http://www.ted.com/talks/*.html
// @exclude http://www.ted.com/talks/*.html?*
// @version 1
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
// @run-at document-start
// @grant none
// @namespace abiteasier.in
// ==/UserScript==
var url = window.location.href;
var talk_name = url.split("/").pop();
talk_name = talk_name.substring(0, talk_name.lastIndexOf('.html'));
var youtube_search_url = 'http://www.youtube.com/user/TEDtalksDirector/search?query=' + talk_name;
window.location.href = youtube_search_url;
$(document).ready( function() {
alert("called");
var a = $("li.channels-browse-content-list-item");
alert(a.length());
} );
正如你可能已经推断的那样,脚本是从TED演讲页面重定向到相应的Youtube视频。我已经完成了搜索,搜索页面加载良好,但.ready函数似乎从未启动。这是由于上面的@run引起的问题吗?Greasemonkey只将其应用于原始TED页面还是应用于我们从脚本访问的每个页面?或者问题在剧本的其他地方?
更新:好吧,我考虑过了,我能想到的最合理的逻辑是,一旦URL更改,GM就会停止执行这个脚本。我会尝试在通用汽车文档中验证这一点,如果你在这方面有知识,请发表回答或评论。
更新2:我通过将YouTube页面包含在@include中修复了这个问题,代码在http://userscripts.org/scripts/show/174390如果有人好奇的话。
警报没有触发有两个原因:
-
浏览器会立即从
www.ted.com
重定向到www.youtube.com
——早在ready
事件在ted.com
上启动之前。脚本根本没有设置为在youtube.com
上激发。如果希望脚本在两个域上启动,请调整
@include
(或@match
)指令,然后使用以下检查:if (location.hostname == "www.ted.com") { var url = window.location.href; var talk_name = url.split("/").pop(); talk_name = talk_name.substring(0, talk_name.lastIndexOf('.html')); var youtube_search_url = 'http://www.youtube.com/user/TEDtalksDirector/search?query=' + talk_name; window.location.href = youtube_search_url; }
以更改每个域的脚本行为。
-
因为使用了
@grant none
,所以GM脚本的jQuery与两个域上的代码冲突。您将在Firefox的错误控制台上看到错误消息(CtrlShift<kbd&J>
相关文章:
- 如何在收到电子邮件时自动调用脚本
- jQuery:调用脚本时隐藏元素
- 如何通过 ajax 跨域调用脚本
- PHP:更改调用脚本的环境
- PHP调用脚本函数,返回值为Uncaught SyntaxError:意外的令牌ILLEGAL
- 将背景图像更改为另一个由ajax调用脚本动态创建的图像
- 有没有办法从 Javascript 中的函数中调用脚本标签和样式标签
- 也需要为“加载”调用脚本,而不仅仅是在“模糊”上
- 如何使用 onclick 按 id 调用脚本
- 使用 jQuery 调用脚本以及 if 语句中的参数
- 如何在显示网页时调用脚本 jquery
- C# asp.net MVC - 使用参数从 html.actionlink 调用脚本函数
- Javascript 表单验证不起作用 - 未调用脚本
- jQuery 获取对调用脚本标记的引用
- 通过 ajax 调用多个脚本.只有在脚本 1 完成执行后,才应调用脚本 2
- 哪个更好:在调用脚本时包含或 src
- 调用脚本时出现 Google 应用脚本关闭错误
- 未调用脚本 JS
- 如何获取从中调用脚本的页面名称
- 在Java中从某个URL调用脚本