JavaScript模拟鼠标点击不工作(谷歌Chrome扩展)

Simulating Mouse Click on JavaScript Isn't Working (Google Chrome Extension)

本文关键字:谷歌 Chrome 扩展 工作 模拟 鼠标 JavaScript      更新时间:2023-09-26

我刚开始使用Javascript,所以在这一点上有点令人困惑。我很抱歉我在这个问题上缺乏知识,但是这个问题真的开始让我沮丧了。

我试图模拟网页youtubemp3.org的点击,但我似乎无法让它工作。我看遍了这个论坛,尝试了不同的片段和其他网站,但没有运气。

manifest.json

{
  "name": "Event Page Example",
  "description": "Demonstrates usage and features of the event page",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["alarms", "tabs", "bookmarks", "declarativeWebRequest", "*://*/*", "http://*/*", "https://*/*"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon" : "icon.png",
    "default_title": "Start Event Page"
  },
  "content_scripts": [
    {
      "js": ["myscript.js"]
    }
  ],
  "commands": {
    "open-google": {
      "description": "Open a tab to google.com",
      "suggested_key": { "default": "Ctrl+Shift+L" }
    },
    "_execute_browser_action": {
      "suggested_key": { "default": "Ctrl+Shift+K" }
    }
  }
}

background.js

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Global variables only exist for the life of the page, so they get reset
// each time the page is unloaded.
var counter = 1;
var youtubeURL = "";
var lastTabId = -1;
function sendMessage() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    lastTabId = tabs[0].id;
    chrome.tabs.sendMessage(lastTabId, "Background page started.");
  });
}
sendMessage();
chrome.browserAction.setBadgeText({text: "ON"});
console.log("Loaded.");
chrome.runtime.onInstalled.addListener(function() {
  console.log("Installed.");
  // localStorage is persisted, so it's a good place to keep state that you
  // need to persist across page reloads.
  localStorage.counter = 1;
  // Register a webRequest rule to redirect bing to google.
  var wr = chrome.declarativeWebRequest;
  chrome.declarativeWebRequest.onRequest.addRules([{
    id: "0",
    conditions: [new wr.RequestMatcher({url: {hostSuffix: "bing.com"}})],
    actions: [new wr.RedirectRequest({redirectUrl: "http://google.com"})]
  }]);
});
function doAClickFFS()
{ 
 chrome.tabs.executeScript(null, {file: "myscript.js", "run_at": "document_end"});
}
chrome.browserAction.onClicked.addListener(function() {
  // The event page will unload after handling this event (assuming nothing
  // else is keeping it awake). The content script will become the main way to
  // interact with us.
  chrome.tabs.create({url: "http://www.youtube-mp3.org"}, function(tab) {
  chrome.tabs.executeScript(tab.id, {code: "document.getElementById('youtube-url').value = 'TEST';"});
  doAClickFFS();
  });
});
chrome.commands.onCommand.addListener(function(command) {
  chrome.tabs.create({url: "http://www.google.com/"});
});

myscript.js

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;
    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }
    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}
function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}
var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}
simulate(document.getElementById('#submit'), 'click');

我已经能够访问和修改页面上的文本框,但无法模拟点击按钮。再一次,我知道这个问题已经回答了十几次在这个论坛上,但没有一个答案已经解决了我的问题。它很可能在我的脑海里,因为我还不太了解Javascript。

快速浏览表明这只是一个时间问题。myscript.js是在构建DOM之前注入的,因此没有按钮可单击。等待页面准备好或在准备好时注入。

另外,您的content_scripts键缺少必需的字段。

https://developer.chrome.com/extensions/content_scripts