尝试使用我的chrome扩展程序单击页面上的元素

时间:2012-12-10 23:55:30

标签: javascript google-chrome google-chrome-extension

我正在尝试创建一个可以从hiphopdx下载mp3的chrome扩展程序。我发现一旦你点击网站上的播放按钮,就可以提取mp3的下载链接。但是我坚持让我的扩展程序单击播放按钮。 以下是我使用扩展程序的页面示例: http://www.hiphopdx.com/index/singles/id.16603/title.fred-the-godson-f-the-kid-daytona-back-to-school-prod-kaimbr

我的清单json

"name": "My Test",
"version": "1",
"manifest_version": 2,
"background": {
    "scripts": ["popup.js"]
},
"browser_action": {
    "default_icon": "icon.png"
},
"permissions": ["tabs", "http://*/*", "https://*/*"]

我的popup.html

<!doctype html>
<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>

popup.js

function ShowOperationMessage(obj, evt) {
        var fireOnThis = obj;
        if (document.createEvent) {
            var evObj = document.createEvent('MouseEvents');
            evObj.initEvent(evt, true, false);
            fireOnThis.dispatchEvent(evObj);
        } else if (document.createEventObject) {
            fireOnThis.fireEvent('on' + evt);
        }
    }

ShowOperationMessage(document.getElementsByClassName("playBtns medium awesome red adjust launchplayer left"),"click");

1 个答案:

答案 0 :(得分:0)

将代码修改为内容脚本代码,我可以点击按钮

enter image description here

<强>参考

添加内容脚本部分以消除背景内容

<强> 的manifest.json

{
    "name": "Mouse Clicks",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "This demonstrates how mouse clicks are tracked",
    "content_scripts": [
    {
      "matches": ["http://www.hiphopdx.com/index/singles/id.16603/title.fred-the-godson-f-the-kid-daytona-back-to-school-prod-kaimbr"],
      "js": ["myscript.js"]
      }
  ]

}

<强> myscript.js

document.getElementsByClassName("playBtns medium awesome red adjust launchplayer left")返回一个使用obj[0]索引

的数组
function ShowOperationMessage(obj, evt) {
    var fireOnThis = obj[0];
    if (document.createEvent) {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent(evt, true, false);
        fireOnThis.dispatchEvent(evObj);
    } else if (document.createEventObject) {
        fireOnThis.fireEvent('on' + evt);
    }
}

ShowOperationMessage(document.getElementsByClassName("playBtns medium awesome red adjust launchplayer left"), "click");

如果您需要更多信息,请与我们联系。