gpt4 book ai didi

javascript - 页面重定向后如何调用Chrome扩展功能?

转载 作者:行者123 更新时间:2023-12-02 22:08:25 25 4
gpt4 key购买 nike

我正在致力于构建一个 Javascript(浏览器内)Instagram 机器人。然而,我遇到了一个问题。

如果运行此脚本,第一个函数将被调用,页面将被重定向到“https://www.instagram.com/explore/tags/samplehashtag/ ”,第二个函数将立即被调用(在页面更改为新 URL 之前的上一个 URL 上) 。有没有办法让第二个函数在第二个 URL 完全加载后被调用?

我尝试将其设置为 Window setInterval() 方法以延长时间段、window.onload 和其他一些方法。但是,我似乎无法做任何事情。有人有解决方案吗?

这是我的第一个 chrome 扩展,也是我的第一个真正的项目,所以我可能会错过一些简单的东西..

list .json

    {
"name": "Inject Me",
"version": "1.0",
"manifest_version": 2,
"description": "Injecting stuff",
"homepage_url": "http://danharper.me",
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "Inject!"
},
"permissions": [
"https://*/*",
"http://*/*",
"tabs"
]
}

注入(inject).js

  (function() {

let findUrl = () => {
let hashtag = "explore/tags/samplehashtag/";
location.replace("https://www.instagram.com/" + hashtag);
}

findUrl();
})();

背景.js

    // this is the background code...

// listen for our browerAction to be clicked
chrome.browserAction.onClicked.addListener(function(tab) {
// for the current tab, inject the "inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
file: 'inject.js'
});

});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {

chrome.tabs.executeScript(tab.ib, {
file: 'inject2.js'
});


});

注入(inject)2.js

(function() {

if (window.location.href.indexOf("https://www.instagram.com/explore/tags/samplehashtag/") != -1){
let likeAndRepeat = () => {
let counter = 0;
let grabPhoto = document.querySelector('._9AhH0');

grabPhoto.click();

let likeAndSkip = function() {
let heart = document.querySelector('.glyphsSpriteHeart__outline__24__grey_9.u-__7');
let arrow = document.querySelector('a.coreSpriteRightPaginationArrow');

if (heart) {
heart.click();
counter++;
console.log(`You have liked ${counter} photographs`)
}
arrow.click();
}

setInterval(likeAndSkip, 3000);
//alert('likeAndRepeat Inserted');
};

likeAndRepeat();

}
})();

最佳答案

从问题和示例中不清楚您何时要运行函数。但是在 chrome 扩展中有一种叫做消息传递

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

通过消息传递,您可以将消息从一个文件传递到另一个文件,并类似地监听消息。因此,从您的用例来看,您可以监听特定消息,然后触发您的方法。

例如

background.js

chrome.runtime.sendMessage({message: "FIRE_SOME_METHOD"})


popup.js

chrome.runtime.onMessage.addListener(
function(request) {

if (request.message == "FIRE_SOME_METHOD")
someMethod();
});

编辑另外,如果您想监听 URL 更改,您可以简单地放置一个监听器,如 documentation 中提供的。 .

  chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
console.log('updated tab');
});

关于javascript - 页面重定向后如何调用Chrome扩展功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59639557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com