我尝试在Twitter的.com网页上发起点击事件。但不知何故,当我在扩展程序中尝试代码时,它不起作用。
if(typeof TIP == 'undefined'){
var TIP = {};
}
TIP.Tweets = {
getNumberOfTweets: function(){
var tweets = $('#stream-items-id .js-stream-item').length;
return tweets;
},
setNumberOfTweets: function(number){
TIP.Tweets.currentNumberOfTweets = number;
}
}
TIP.initiate = function(){
TIP.Tweets.currentNumberOfTweet = TIP.Tweets.getNumberOfTweets();
setInterval(function(){
var tweets = TIP.Tweets.getNumberOfTweets();
if(TIP.Tweets.currentNumberOfTweets != tweets){
TIP.Tweets.setNumberOfTweets(tweets);
TIP.renderImages();
}
}, 100);
//Render images
TIP.renderImages();
}
TIP.renderImages = function(){
$('#stream-items-id .js-view-details').each(function(){
var btn = this
if($.trim($(this).text()) == 'View photo'){
$(btn).click();//This is the button I want to click, which is the view photo button
console.log('rendered');
}
});
}
$(function(){
TIP.initiate();
});
但是,当我尝试手动插入代码时,它可以工作。我在Google Chrome控制台中插入以下代码:
$('#stream-items-id .js-view-details').each(function(){
var btn = this
if($.trim($(this).text()) == 'View photo'){
$(btn).click();
console.log('rendered');
}
});
如果我尝试做其他事情而不是发起点击事件。它工作正常。例如,如果我想操纵按钮的内部html。它在扩展代码中工作正常。只有当我尝试在扩展程序中启动单击时才会出现此问题。
请求manifest.json文件:
{
"name": "Twitter Image Previewer",
"version": "1.0",
"description": "Enables image previews in tweets",
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": ["http://twitter.com/*", "https://twitter.com/*"],
"css": ["style.css"],
"js": ["jquery.min.js", "JeasyCreate.js", "extension.js"],
"all_frames": true
}
],
"permissions": [
"http://*/",
"https://*/"
]
}
答案 0 :(得分:1)
我对JQuery一无所知但认为我应该指出它确实可以作为一种更纯粹的JS方式工作....
// https://developer.mozilla.org/en/DOM/element.dispatchEvent
function simulateClick(obj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var canceled = !obj.dispatchEvent(evt);
/*
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
*/
}
var photos = document.querySelectorAll('#stream-items-id .js-view-details');
for (var i = 0; i < photos.length; i++) {
if (photos[i].firstChild.data.trim()=='View photo') simulateClick(photos[i]);
}