0

I have the following code to get the link to bookmarking a topic on a phpBB forum

var bookmark = document.getElementsByClassName('bookmark-link');
console.log(bookmark)
var bookmark_array = Array.from(bookmark);
console.log(bookmark_array)
bookmark_array.length = 1;
console.log(bookmark_array)
var str = bookmark_array.toString();
console.log(str)
var link = str.match('\/viewtopic\.php\?f=(\d+)&t=(\d+)&bookmark=1&hash=(\w+)');
console.log(link)
window.open(link);
setTimeout(() => {  window.close(link); }, 3000);

(console logs are just to visualize what's going on)

But window.open goes to a url like https://my.site.com/null in the end

The console log for link however shows the correct link I want to go to

When I execute it manually (copying the url from console.log(link) output, then doing window.open("what I copied") it works just fine

I assumed it's the issue with quotes, but enclosing link in them will result in https://my.site.com/"null"

I have popups enabled in Chrome for that site and it's whitelisted in all my adblockers.

So I'm really in the dark as to the reason why this happens

Thank you!

8
  • 1
    str.match() returns an array, not a string. Commented Jul 14, 2020 at 21:23
  • @Barmar How should I go about fixing it? .toString returns Uncaught TypeError: Cannot read property 'toString' of null. I want to keep the code structure as is, since it's my first day coding in JS, so even though it's not very good at least I understand how it works Commented Jul 14, 2020 at 21:35
  • If you're getting null, it means it didn't match the regexp. Commented Jul 14, 2020 at 21:35
  • That's why the URL is null. Commented Jul 14, 2020 at 21:35
  • There are many strange things in your code. Why do you set the array length to 1? If you just want the first element, use bookmark_array[0]. Commented Jul 14, 2020 at 21:36

1 Answer 1

1

Your code has lots of unnecessary complexity. I've simplified it below.

The reason you're going to null is because the bookmark doesn't match the pattern you're testing with str.match(), so it returns null. You need to check for that.

var bookmark = document.getElementsByClassName('bookmark-link');
console.log(bookmark)
var first_bookmark = bookmark[0];
var url = first_bookmark.href;
console.log(url)
var link = url.match(/\/viewtopic\.php\?f=(\d+)&t=(\d+)&bookmark=1&hash=(\w+)/);
if (link) {
    window.open(url);
    setTimeout(() => {  window.close(link); }, 3000);
} else {
    alert("Bookmark link doesn't match the pattern");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.